summaryrefslogtreecommitdiff
path: root/mv_inference/inference/src/Inference.cpp
blob: d7e13f99fbd16a1d60ab67aee2d387303f36e4b3 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
/**
 * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mv_private.h"
#include "Inference.h"
#include "InferenceIni.h"

#include <map>

#include <unistd.h>
#include <fstream>
#include <string>
#include <queue>
#include <algorithm>

#define MV_INFERENCE_OUTPUT_NUMBERS_MAX 10
#define MV_INFERENCE_OUTPUT_NUMBERS_MIN 1
#define MV_INFERENCE_CONFIDENCE_THRESHOLD_MAX 1.0
#define MV_INFERENCE_CONFIDENCE_THRESHOLD_MIN 0.0

typedef enum {
	InputAttrNoType = 0,
	InputAttrFloat32 = 1,
	InputAttrInt32 = 2,
	InputAttrUInt8 = 3,
	InputAttrInt64 = 4,
	InputAttrString = 5,
	InputAttrBool = 6,
} InputAttrType;

namespace mediavision
{
namespace inference
{
	InferenceConfig::InferenceConfig() :
			mConfigFilePath(),
			mWeightFilePath(),
			mUserFilePath(),
			mDataType(MV_INFERENCE_DATA_FLOAT32),
			mBackedType(MV_INFERENCE_BACKEND_NONE),
			mTargetTypes(MV_INFERENCE_TARGET_NONE),
			mConfidenceThresHold(),
			mMeanValue(),
			mStdValue(),
			mMaxOutputNumbers(1)
	{
		mTensorInfo.width = -1;
		mTensorInfo.height = -1;
		mTensorInfo.dim = -1;
		mTensorInfo.ch = -1;
	}

	Inference::Inference() :
			mCanRun(),
			mConfig(),
			mBackendCapacity(),
			mSupportedInferenceBackend(),
			mInputSize(cv::Size()),
			mCh(),
			mDim(),
			mDeviation(),
			mMean(),
			mThreshold(),
			mOutputNumbers(),
			mSourceSize(cv::Size()),
			mInputBuffer(cv::Mat()),
			engine_config(),
			mBackend()
	{
		LOGI("ENTER");

		mSupportedInferenceBackend.insert(std::make_pair(
				MV_INFERENCE_BACKEND_OPENCV, std::make_pair("opencv", false)));
		mSupportedInferenceBackend.insert(std::make_pair(
				MV_INFERENCE_BACKEND_TFLITE, std::make_pair("tflite", false)));
		mSupportedInferenceBackend.insert(std::make_pair(
				MV_INFERENCE_BACKEND_ARMNN, std::make_pair("armnn", false)));
		mSupportedInferenceBackend.insert(std::make_pair(
				MV_INFERENCE_BACKEND_MLAPI, std::make_pair("mlapi", false)));
		mSupportedInferenceBackend.insert(std::make_pair(
				MV_INFERENCE_BACKEND_ONE, std::make_pair("mlapi", false)));

		CheckSupportedInferenceBackend();

		for (int i = 0; i < MV_INFERENCE_BACKEND_MAX; ++i) {
			auto iter = mSupportedInferenceBackend.find(i);
			LOGE("%d: %s: %s", i, (iter->second).first.c_str(),
				 (iter->second).second ? "TRUE" : "FALSE");
		}

		mModelFormats.insert(std::make_pair<std::string, int>(
				"caffemodel", INFERENCE_MODEL_CAFFE));
		mModelFormats.insert(
				std::make_pair<std::string, int>("pb", INFERENCE_MODEL_TF));
		mModelFormats.insert(std::make_pair<std::string, int>(
				"tflite", INFERENCE_MODEL_TFLITE));
		mModelFormats.insert(
				std::make_pair<std::string, int>("t7", INFERENCE_MODEL_TORCH));
		mModelFormats.insert(std::make_pair<std::string, int>(
				"weights", INFERENCE_MODEL_DARKNET));
		mModelFormats.insert(
				std::make_pair<std::string, int>("bin", INFERENCE_MODEL_DLDT));
		mModelFormats.insert(
				std::make_pair<std::string, int>("onnx", INFERENCE_MODEL_ONNX));
		mModelFormats.insert(std::make_pair<std::string, int>(
				"nb", INFERENCE_MODEL_VIVANTE));

		LOGI("LEAVE");
	}

	Inference::~Inference()
	{
		CleanupTensorBuffers();

		if (!mInputLayerProperty.tensor_infos.empty()) {
			mInputLayerProperty.tensor_infos.clear();
			std::vector<inference_engine_tensor_info>().swap(
					mInputLayerProperty.tensor_infos);
		}
		if (!mOutputLayerProperty.tensor_infos.empty()) {
			mOutputLayerProperty.tensor_infos.clear();
			std::vector<inference_engine_tensor_info>().swap(
					mOutputLayerProperty.tensor_infos);
		}

		mModelFormats.clear();

		// Release backend engine.
		if (mBackend) {
			mBackend->UnbindBackend();
			delete mBackend;
		}

		LOGI("Released backend engine.");
	}

	void Inference::CheckSupportedInferenceBackend()
	{
		LOGE("ENTER");

		InferenceInI ini;
		ini.LoadInI();

		std::vector<int> supportedBackend = ini.GetSupportedInferenceEngines();
		for (std::vector<int>::const_iterator it = supportedBackend.begin();
			 it != supportedBackend.end(); ++it) {
			LOGE("engine: %d", *it);

			auto iter = mSupportedInferenceBackend.find(*it);
			(iter->second).second = true;
		}

		LOGE("LEAVE");
	}

	int Inference::ConvertEngineErrorToVisionError(int error)
	{
		int ret = MEDIA_VISION_ERROR_NONE;

		switch (error) {
		case INFERENCE_ENGINE_ERROR_NONE:
			ret = MEDIA_VISION_ERROR_NONE;
			break;
		case INFERENCE_ENGINE_ERROR_NOT_SUPPORTED:
			ret = MEDIA_VISION_ERROR_NOT_SUPPORTED;
			break;
		case INFERENCE_ENGINE_ERROR_MSG_TOO_LONG:
			ret = MEDIA_VISION_ERROR_MSG_TOO_LONG;
			break;
		case INFERENCE_ENGINE_ERROR_NO_DATA:
			ret = MEDIA_VISION_ERROR_NO_DATA;
			break;
		case INFERENCE_ENGINE_ERROR_KEY_NOT_AVAILABLE:
			ret = MEDIA_VISION_ERROR_KEY_NOT_AVAILABLE;
			break;
		case INFERENCE_ENGINE_ERROR_OUT_OF_MEMORY:
			ret = MEDIA_VISION_ERROR_OUT_OF_MEMORY;
			break;
		case INFERENCE_ENGINE_ERROR_INVALID_PARAMETER:
			ret = MEDIA_VISION_ERROR_INVALID_PARAMETER;
			break;
		case INFERENCE_ENGINE_ERROR_INVALID_OPERATION:
			ret = MEDIA_VISION_ERROR_INVALID_OPERATION;
			break;
		case INFERENCE_ENGINE_ERROR_PERMISSION_DENIED:
			ret = MEDIA_VISION_ERROR_PERMISSION_DENIED;
			break;
		case INFERENCE_ENGINE_ERROR_NOT_SUPPORTED_FORMAT:
			ret = MEDIA_VISION_ERROR_NOT_SUPPORTED_FORMAT;
			break;
		case INFERENCE_ENGINE_ERROR_INTERNAL:
			ret = MEDIA_VISION_ERROR_INTERNAL;
			break;
		case INFERENCE_ENGINE_ERROR_INVALID_DATA:
			ret = MEDIA_VISION_ERROR_INVALID_DATA;
			break;
		case INFERENCE_ENGINE_ERROR_INVALID_PATH:
			ret = MEDIA_VISION_ERROR_INVALID_PATH;
			break;
		default:
			LOGE("Unknown inference engine error type");
		}

		return ret;
	}

	int Inference::ConvertTargetTypes(int given_types)
	{
		int target_types = INFERENCE_TARGET_NONE;

		if (given_types & MV_INFERENCE_TARGET_DEVICE_CPU)
			target_types |= INFERENCE_TARGET_CPU;
		if (given_types & MV_INFERENCE_TARGET_DEVICE_GPU)
			target_types |= INFERENCE_TARGET_GPU;
		if (given_types & MV_INFERENCE_TARGET_DEVICE_CUSTOM)
			target_types |= INFERENCE_TARGET_CUSTOM;

		return target_types;
	}

	int Inference::ConvertToCv(int given_type)
	{
		int type = 0;

		switch (given_type) {
		case INFERENCE_TENSOR_DATA_TYPE_UINT8:
			LOGI("Type is %d ch with UINT8", mCh);
			type = mCh == 1 ? CV_8UC1 : CV_8UC3;
			break;
		case INFERENCE_TENSOR_DATA_TYPE_FLOAT32:
			LOGI("Type is %d ch with FLOAT32", mCh);
			type = mCh == 1 ? CV_32FC1 : CV_32FC3;
			break;
		default:
			LOGI("unknown data type so FLOAT32 data type will be used in default");
			type = mCh == 1 ? CV_32FC1 : CV_32FC3;
			break;
		}

		return type;
	}

	inference_tensor_data_type_e Inference::ConvertToIE(int given_type)
	{
		inference_tensor_data_type_e type = INFERENCE_TENSOR_DATA_TYPE_FLOAT32;

		switch (given_type) {
		case MV_INFERENCE_DATA_FLOAT32:
			type = INFERENCE_TENSOR_DATA_TYPE_FLOAT32;
			break;
		case MV_INFERENCE_DATA_UINT8:
			type = INFERENCE_TENSOR_DATA_TYPE_UINT8;
			break;
		default:
			LOGI("unknown data type so FLOAT32 data type will be used in default");
			break;
		}

		return type;
	}

	int Inference::Preprocess(cv::Mat cvImg, cv::Mat cvDst, int data_type)
	{
		mSourceSize = cvImg.size();
		int width = mInputSize.width;
		int height = mInputSize.height;

		cv::Mat sample;
		if (cvImg.channels() == 3 && mCh == 1)
			cv::cvtColor(cvImg, sample, cv::COLOR_BGR2GRAY);
		else
			sample = cvImg;

		// size
		cv::Mat sampleResized;
		if (sample.size() != cv::Size(width, height))
			cv::resize(sample, sampleResized, cv::Size(width, height));
		else
			sampleResized = sample;

		// type
		cv::Mat sampleFloat;
		if (mCh == 3)
			sampleResized.convertTo(sampleFloat, CV_32FC3);
		else
			sampleResized.convertTo(sampleFloat, CV_32FC1);

		// normalize
		cv::Mat sampleNormalized;
		cv::Mat meanMat;
		if (mCh == 3)
			meanMat = cv::Mat(sampleFloat.size(), CV_32FC3,
							  cv::Scalar((float) mMean, (float) mMean,
							  (float) mMean));
		else
			meanMat = cv::Mat(sampleFloat.size(), CV_32FC1,
							  cv::Scalar((float) mMean));

		cv::subtract(sampleFloat, meanMat, sampleNormalized);

		sampleNormalized /= static_cast<float>(mDeviation);

		sampleNormalized.convertTo(cvDst, data_type);

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::SetUserFile(std::string filename)
	{
		std::ifstream fp(filename.c_str());
		if (!fp.is_open()) {
			return MEDIA_VISION_ERROR_INVALID_PATH;
		}

		std::string userListName;
		while (!fp.eof()) {
			std::getline(fp, userListName);
			if (userListName.length())
				mUserListName.push_back(userListName);
		}

		fp.close();

		return MEDIA_VISION_ERROR_NONE;
	}

	void Inference::ConfigureModelFiles(const std::string modelConfigFilePath,
										const std::string modelWeightFilePath,
										const std::string modelUserFilePath)
	{
		LOGI("ENTER");

		mConfig.mConfigFilePath = modelConfigFilePath;
		mConfig.mWeightFilePath = modelWeightFilePath;
		mConfig.mUserFilePath = modelUserFilePath;

		LOGI("LEAVE");
	}

	void Inference::ConfigureTensorInfo(int width, int height, int dim, int ch,
										double stdValue, double meanValue)
	{
		LOGI("ENTER");

		mConfig.mTensorInfo = { width, height, dim, ch };
		mConfig.mStdValue = stdValue;
		mConfig.mMeanValue = meanValue;

		LOGI("LEAVE");
	}

	void Inference::ConfigureInputInfo(int width, int height, int dim, int ch,
									   double stdValue, double meanValue,
									   int dataType,
									   const std::vector<std::string> names)
	{
		LOGI("ENTER");

		mConfig.mTensorInfo = { width, height, dim, ch };
		mConfig.mStdValue = stdValue;
		mConfig.mMeanValue = meanValue;
		mConfig.mDataType = static_cast<mv_inference_data_type_e>(dataType);
		mConfig.mInputLayerNames = names;

		inference_engine_layer_property property;
		// In case of that a inference plugin deosn't support to get properties,
		// the tensor info given by a user will be used.
		// If the plugin supports that, the given info will be ignored.
		inference_engine_tensor_info tensor_info;

		tensor_info.data_type = ConvertToIE(dataType);

		// In case of OpenCV, only supports NCHW
		tensor_info.shape_type = INFERENCE_TENSOR_SHAPE_NCHW;
		// modify to handle multiple tensor infos
		tensor_info.shape.push_back(mConfig.mTensorInfo.dim);
		tensor_info.shape.push_back(mConfig.mTensorInfo.ch);
		tensor_info.shape.push_back(mConfig.mTensorInfo.height);
		tensor_info.shape.push_back(mConfig.mTensorInfo.width);

		tensor_info.size = 1;
		for (std::vector<size_t>::iterator iter = tensor_info.shape.begin();
			 iter != tensor_info.shape.end(); ++iter) {
			tensor_info.size *= (*iter);
		}

		property.layer_names = mConfig.mInputLayerNames;
		property.tensor_infos.push_back(tensor_info);

		int ret = mBackend->SetInputLayerProperty(property);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to set input layer property");
		}

		LOGI("LEAVE");
	}

	void Inference::ConfigureOutputInfo(const std::vector<std::string> names)
	{
		LOGI("ENTER");

		mConfig.mOutputLayerNames = names;

		inference_engine_layer_property property;

		property.layer_names = names;
		int ret = mBackend->SetOutputLayerProperty(property);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to set output layer property");
		}

		LOGI("LEAVE");
	}

	int Inference::ConfigureBackendType(
			const mv_inference_backend_type_e backendType)
	{
		std::pair<std::string, bool> backend =
				mSupportedInferenceBackend[backendType];
		if (backend.second == false) {
			LOGE("%s type is not supported", (backend.first).c_str());
			return MEDIA_VISION_ERROR_NOT_SUPPORTED_FORMAT;
		}

		LOGI("backend engine : %d", backendType);

		mConfig.mBackedType = backendType;

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::ConfigureTargetTypes(const int targetType)
	{
		// Check if given target types are valid or not.
		if (MV_INFERENCE_TARGET_NONE >= targetType ||
			MV_INFERENCE_TARGET_MAX <= targetType) {
			LOGE("Invalid target device.");
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		LOGI("Before convering target types : %d", targetType);

		unsigned int new_type = MV_INFERENCE_TARGET_DEVICE_NONE;

		// Convert old type to new one.
		switch (targetType) {
		case MV_INFERENCE_TARGET_CPU:
			new_type = MV_INFERENCE_TARGET_DEVICE_CPU;
			break;
		case MV_INFERENCE_TARGET_GPU:
			new_type = MV_INFERENCE_TARGET_DEVICE_GPU;
			break;
		case MV_INFERENCE_TARGET_CUSTOM:
			new_type = MV_INFERENCE_TARGET_DEVICE_CUSTOM;
			break;
		}

		LOGI("After convering target types : %d", new_type);

		mConfig.mTargetTypes = new_type;

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::ConfigureTargetDevices(const int targetDevices)
	{
		// Check if given target types are valid or not.
		if (MV_INFERENCE_TARGET_DEVICE_NONE >= targetDevices ||
			MV_INFERENCE_TARGET_DEVICE_MAX <= targetDevices) {
			LOGE("Invalid target device.");
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		LOGI("target devices : %d", targetDevices);

		mConfig.mTargetTypes = targetDevices;

		return MEDIA_VISION_ERROR_NONE;
	}

	void Inference::ConfigureOutput(const int maxOutputNumbers)
	{
		mConfig.mMaxOutputNumbers = std::max(
				std::min(maxOutputNumbers, MV_INFERENCE_OUTPUT_NUMBERS_MAX),
				MV_INFERENCE_OUTPUT_NUMBERS_MIN);
	}

	void Inference::ConfigureThreshold(const double threshold)
	{
		mConfig.mConfidenceThresHold = std::max(
				std::min(threshold, MV_INFERENCE_CONFIDENCE_THRESHOLD_MAX),
				MV_INFERENCE_CONFIDENCE_THRESHOLD_MIN);
	}

	void Inference::CleanupTensorBuffers(void)
	{
		LOGI("ENTER");

		if (!mInputTensorBuffers.empty()) {
			std::vector<inference_engine_tensor_buffer>::iterator iter;
			for (iter = mInputTensorBuffers.begin();
				 iter != mInputTensorBuffers.end(); iter++) {
				inference_engine_tensor_buffer tensor_buffer = *iter;

				// If tensor buffer owner is a backend then skip to release the tensor buffer.
				// This tensor buffer will be released by the backend.
				if (tensor_buffer.owner_is_backend) {
					continue;
				}

				if (tensor_buffer.data_type ==
					INFERENCE_TENSOR_DATA_TYPE_FLOAT32)
					delete[] static_cast<float *>(tensor_buffer.buffer);
				else
					delete[] static_cast<unsigned char *>(tensor_buffer.buffer);
			}

			LOGI("input tensor buffers(%zu) have been released.",
				 mInputTensorBuffers.size());
			std::vector<inference_engine_tensor_buffer>().swap(
					mInputTensorBuffers);
		}

		if (!mOutputTensorBuffers.empty()) {
			std::vector<inference_engine_tensor_buffer>::iterator iter;
			for (iter = mOutputTensorBuffers.begin();
				 iter != mOutputTensorBuffers.end(); iter++) {
				inference_engine_tensor_buffer tensor_buffer = *iter;

				// If tensor buffer owner is a backend then skip to release the tensor buffer.
				// This tensor buffer will be released by the backend.
				if (tensor_buffer.owner_is_backend) {
					continue;
				}

				if (tensor_buffer.data_type ==
					INFERENCE_TENSOR_DATA_TYPE_FLOAT32)
					delete[] static_cast<float *>(tensor_buffer.buffer);
				else
					delete[] static_cast<unsigned char *>(tensor_buffer.buffer);
			}

			LOGI("output tensor buffers(%zu) have been released.",
				 mOutputTensorBuffers.size());
			std::vector<inference_engine_tensor_buffer>().swap(
					mOutputTensorBuffers);
		}

		LOGI("LEAVE");
	}

	int Inference::PrepareTenosrBuffers(void)
	{
		// If there are input and output tensor buffers allocated before then release the buffers.
		// They will be allocated again according to a new model file to be loaded.
		CleanupTensorBuffers();

		// IF model file is loaded again then the model type could be different so
		// clean up input and output layer properties so that they can be updated again
		// after reloading the model file.
		if (!mInputLayerProperty.tensor_infos.empty()) {
			mInputLayerProperty.tensor_infos.clear();
			std::vector<inference_engine_tensor_info>().swap(
					mInputLayerProperty.tensor_infos);
		}
		if (!mOutputLayerProperty.tensor_infos.empty()) {
			mOutputLayerProperty.tensor_infos.clear();
			std::vector<inference_engine_tensor_info>().swap(
					mOutputLayerProperty.tensor_infos);
		}

		// Get input tensor buffers from a backend engine if the backend engine allocated.
		int ret = mBackend->GetInputTensorBuffers(mInputTensorBuffers);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to get input tensor buffers from backend engine.");
			return ConvertEngineErrorToVisionError(ret);
		}

		ret = mBackend->GetInputLayerProperty(mInputLayerProperty);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to get input layer property from backend engine.");
			return ConvertEngineErrorToVisionError(ret);
		}

		// If the backend engine isn't able to allocate input tensor buffers internally,
		// then allocate the buffers at here.
		if (mInputTensorBuffers.empty()) {
			for (int i = 0; i < mInputLayerProperty.tensor_infos.size(); ++i) {
				inference_engine_tensor_info tensor_info =
						mInputLayerProperty.tensor_infos[i];
				inference_engine_tensor_buffer tensor_buffer;
				if (tensor_info.data_type ==
					INFERENCE_TENSOR_DATA_TYPE_FLOAT32) {
					tensor_buffer.buffer = new float[tensor_info.size];
					tensor_buffer.size = tensor_info.size * 4;
				} else if (tensor_info.data_type ==
						   INFERENCE_TENSOR_DATA_TYPE_UINT8) {
					tensor_buffer.buffer = new unsigned char[tensor_info.size];
					tensor_buffer.size = tensor_info.size;
				} else if (tensor_info.data_type ==
						   INFERENCE_TENSOR_DATA_TYPE_UINT16) {
					tensor_buffer.buffer = new short[tensor_info.size];
					tensor_buffer.size = tensor_info.size;
				} else {
					LOGE("Invalid input tensor data type.");
					return MEDIA_VISION_ERROR_INVALID_PARAMETER;
				}

				if (tensor_buffer.buffer == NULL) {
					LOGE("Fail to allocate input tensor buffer.");
					return MEDIA_VISION_ERROR_OUT_OF_MEMORY;
				}

				LOGI("Allocated input tensor buffer(size = %zu, data type = %d)",
					 tensor_info.size, tensor_info.data_type);
				tensor_buffer.owner_is_backend = 0;
				tensor_buffer.data_type = tensor_info.data_type;
				mInputTensorBuffers.push_back(tensor_buffer);
			}
		}

		LOGI("Input tensor buffer count is %zu", mInputTensorBuffers.size());

		// Get output tensor buffers from a backend engine if the backend engine allocated.
		ret = mBackend->GetOutputTensorBuffers(mOutputTensorBuffers);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to get output tensor buffers from backend engine.");
			return ConvertEngineErrorToVisionError(ret);
		}

		ret = mBackend->GetOutputLayerProperty(mOutputLayerProperty);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to get output layer property from backend engine.");
			return ConvertEngineErrorToVisionError(ret);
		}

		// If the backend engine isn't able to allocate output tensor buffers internally,
		// then allocate the buffers at here.
		if (mOutputTensorBuffers.empty()) {
			for (int i = 0; i < mOutputLayerProperty.tensor_infos.size(); ++i) {
				inference_engine_tensor_info tensor_info =
						mOutputLayerProperty.tensor_infos[i];
				inference_engine_tensor_buffer tensor_buffer;
				if (tensor_info.data_type ==
					INFERENCE_TENSOR_DATA_TYPE_FLOAT32) {
					tensor_buffer.buffer = new float[tensor_info.size];
					tensor_buffer.size = tensor_info.size * 4;
				} else if (tensor_info.data_type ==
						   INFERENCE_TENSOR_DATA_TYPE_UINT8) {
					tensor_buffer.buffer = new char[tensor_info.size];
					tensor_buffer.size = tensor_info.size;
				} else if (tensor_info.data_type ==
						   INFERENCE_TENSOR_DATA_TYPE_UINT16) {
					tensor_buffer.buffer = new short[tensor_info.size];
					tensor_buffer.size = tensor_info.size;
				} else {
					LOGE("Invalid output tensor data type.");
					CleanupTensorBuffers();
					return MEDIA_VISION_ERROR_INVALID_PARAMETER;
				}

				if (tensor_buffer.buffer == NULL) {
					LOGE("Fail to allocate output tensor buffer.");
					CleanupTensorBuffers();
					return MEDIA_VISION_ERROR_OUT_OF_MEMORY;
				}

				LOGI("Allocated output tensor buffer(size = %zu, data type = %d)",
					 tensor_info.size, tensor_info.data_type);

				tensor_buffer.owner_is_backend = 0;
				tensor_buffer.data_type = tensor_info.data_type;
				mOutputTensorBuffers.push_back(tensor_buffer);
			}
		}

		LOGI("Output tensor buffer count is %zu", mOutputTensorBuffers.size());

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::FillOutputResult(tensor_t &outputData)
	{
		for (int i = 0; i < mOutputLayerProperty.tensor_infos.size(); ++i) {
			inference_engine_tensor_info tensor_info =
					mOutputLayerProperty.tensor_infos[i];

			std::vector<int> tmpDimInfo;
			for (int i = 0; i < static_cast<int>(tensor_info.shape.size());
				 i++) {
				tmpDimInfo.push_back(tensor_info.shape[i]);
			}

			outputData.dimInfo.push_back(tmpDimInfo);

			// Normalize output tensor data converting it to float type in case of quantized model.
			if (tensor_info.data_type == INFERENCE_TENSOR_DATA_TYPE_UINT8) {
				float *new_buf = new float[tensor_info.size];
				if (new_buf == NULL) {
					LOGE("Fail to allocate a new output tensor buffer.");
					return MEDIA_VISION_ERROR_OUT_OF_MEMORY;
				}

				unsigned char *ori_buf = static_cast<unsigned char *>(
						mOutputTensorBuffers[i].buffer);

				for (int j = 0; j < tensor_info.size; j++) {
					new_buf[j] = static_cast<float>(ori_buf[j]) / 255.0f;
				}

				// replace original buffer with new one, and release origin one.
				mOutputTensorBuffers[i].buffer = new_buf;

				if (!mOutputTensorBuffers[i].owner_is_backend)
					delete[] ori_buf;
			}

			if (tensor_info.data_type == INFERENCE_TENSOR_DATA_TYPE_UINT16) {
				float *new_buf = new float[tensor_info.size];
				if (new_buf == NULL) {
					LOGE("Fail to allocate a new output tensor buffer.");
					return MEDIA_VISION_ERROR_OUT_OF_MEMORY;
				}

				short *ori_buf =
						static_cast<short *>(mOutputTensorBuffers[i].buffer);

				for (int j = 0; j < tensor_info.size; j++) {
					new_buf[j] = static_cast<float>(ori_buf[j]);
				}

				// replace original buffer with new one, and release origin one.
				mOutputTensorBuffers[i].buffer = new_buf;

				if (!mOutputTensorBuffers[i].owner_is_backend)
					delete[] ori_buf;
			}

			outputData.data.push_back(
					static_cast<void *>(mOutputTensorBuffers[i].buffer));
		}

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::Bind(void)
	{
		LOGI("ENTER");

		if (mConfig.mBackedType <= MV_INFERENCE_BACKEND_NONE ||
			mConfig.mBackedType >= MV_INFERENCE_BACKEND_MAX) {
			LOGE("NOT SUPPORTED BACKEND %d", mConfig.mBackedType);
			return MEDIA_VISION_ERROR_INVALID_OPERATION;
		}

		auto iter = mSupportedInferenceBackend.find(mConfig.mBackedType);
		std::string backendName = (iter->second).first;
		LOGI("backend string name: %s", backendName.c_str());

		inference_engine_config config = {
			.backend_name = backendName,
			.backend_type = mConfig.mBackedType,
			// As a default, Target device is CPU. If user defined desired device type in json file
			// then the device type will be set by Load callback.
			.target_devices = mConfig.mTargetTypes,
		};

		// Create a backend class object.
		try {
			mBackend = new InferenceEngineCommon();
		} catch (const std::bad_alloc &ex) {
			LOGE("Fail to create backend : %s", ex.what());
			return MEDIA_VISION_ERROR_OUT_OF_MEMORY;
		}

		// Bind a backend library.
		int ret = mBackend->BindBackend(&config);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			LOGE("Fail to bind backend library.(%d)", mConfig.mBackedType);
			return MEDIA_VISION_ERROR_INVALID_OPERATION;
		}

		// Get capacity information from a backend.
		ret = mBackend->GetBackendCapacity(&mBackendCapacity);
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to get backend capacity.");
			return ret;
		}

		LOGI("LEAVE");

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::Prepare(void)
	{
		LOGI("ENTER");

		mCh = mConfig.mTensorInfo.ch;
		mDim = mConfig.mTensorInfo.dim;
		mInputSize =
				cv::Size(mConfig.mTensorInfo.width, mConfig.mTensorInfo.height);
		LOGI("InputSize is %d x %d\n", mInputSize.width, mInputSize.height);

		mDeviation = mConfig.mStdValue;
		mMean = mConfig.mMeanValue;
		LOGI("mean %.4f, deviation %.4f", mMean, mDeviation);

		mOutputNumbers = mConfig.mMaxOutputNumbers;
		LOGI("outputNumber %d", mOutputNumbers);

		mThreshold = mConfig.mConfidenceThresHold;
		LOGI("threshold %.4f", mThreshold);

		// Check if backend supports a given target device/devices or not.
		if (mConfig.mTargetTypes & MV_INFERENCE_TARGET_DEVICE_CPU) {
			if (!(mBackendCapacity.supported_accel_devices &
				  INFERENCE_TARGET_CPU)) {
				LOGE("Backend doesn't support CPU device as an accelerator.");
				return MEDIA_VISION_ERROR_INVALID_PARAMETER;
			}
		}

		if (mConfig.mTargetTypes & MV_INFERENCE_TARGET_DEVICE_GPU) {
			if (!(mBackendCapacity.supported_accel_devices &
				  INFERENCE_TARGET_GPU)) {
				LOGE("Backend doesn't support CPU device as an accelerator.");
				return MEDIA_VISION_ERROR_INVALID_PARAMETER;
			}
		}

		if (mConfig.mTargetTypes & MV_INFERENCE_TARGET_DEVICE_CUSTOM) {
			if (!(mBackendCapacity.supported_accel_devices &
				  INFERENCE_TARGET_CUSTOM)) {
				LOGE("Backend doesn't support CPU device as an accelerator.");
				return MEDIA_VISION_ERROR_INVALID_PARAMETER;
			}
		}

		mBackend->SetTargetDevices(ConvertTargetTypes(mConfig.mTargetTypes));

		LOGI("LEAVE");

		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::Load(void)
	{
		LOGI("ENTER");

		std::string label_file = mConfig.mUserFilePath;
		size_t userFileLength = label_file.length();
		if (userFileLength > 0 && access(label_file.c_str(), F_OK)) {
			LOGE("Label file path in [%s] ", label_file.c_str());
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		int ret = (userFileLength > 0) ? SetUserFile(label_file) :
										 MEDIA_VISION_ERROR_NONE;
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to load label file.");
			return ret;
		}

		// Check if model file is valid or not.
		std::string ext_str = mConfig.mWeightFilePath.substr(
				mConfig.mWeightFilePath.find_last_of(".") + 1);
		std::map<std::string, int>::iterator key = mModelFormats.find(ext_str);
		if (key == mModelFormats.end()) {
			LOGE("Invalid model file format.(ext = %s)", ext_str.c_str());
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		LOGI("%s model file has been detected.", ext_str.c_str());

		std::vector<std::string> models;

		inference_model_format_e model_format =
				static_cast<inference_model_format_e>(key->second);

		// Push model file information to models vector properly according to detected model format.
		switch (model_format) {
		case INFERENCE_MODEL_CAFFE:
		case INFERENCE_MODEL_TF:
		case INFERENCE_MODEL_DARKNET:
		case INFERENCE_MODEL_DLDT:
		case INFERENCE_MODEL_ONNX:
		case INFERENCE_MODEL_VIVANTE:
			models.push_back(mConfig.mWeightFilePath);
			models.push_back(mConfig.mConfigFilePath);
			break;
		case INFERENCE_MODEL_TFLITE:
		case INFERENCE_MODEL_TORCH:
			models.push_back(mConfig.mWeightFilePath);
			break;
		default:
			break;
		}

		// Request model loading to backend engine.
		ret = mBackend->Load(models, model_format);
		if (ret != INFERENCE_ENGINE_ERROR_NONE) {
			delete mBackend;
			LOGE("Fail to load model");
			mCanRun = false;
			std::vector<std::string>().swap(models);
			return ConvertEngineErrorToVisionError(ret);
		}

		std::vector<std::string>().swap(models);

		// Prepare input and output tensor buffers.
		PrepareTenosrBuffers();

		mCanRun = true;

		LOGI("LEAVE");

		return ConvertEngineErrorToVisionError(ret);
	}

	int Inference::Run(std::vector<mv_source_h> &mvSources,
					   std::vector<mv_rectangle_s> &rects)
	{
		int ret = INFERENCE_ENGINE_ERROR_NONE;

		if (!mCanRun) {
			LOGE("Invalid to run inference");
			return MEDIA_VISION_ERROR_INVALID_OPERATION;
		}

		/* convert mv_source to cv::Mat */
		cv::Mat cvSource;
		cv::Rect cvRoi;
		unsigned int width = 0, height = 0;
		unsigned int bufferSize = 0;
		unsigned char *buffer = NULL;

		if (mvSources.empty()) {
			LOGE("mvSources should contain only one cv source.");
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		// We are able to request Only one input data for the inference as of now.
		if (mvSources.size() > 1) {
			LOGE("It allows only one mv source for the inference.");
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		// TODO. Consider multiple sources.
		mv_source_h mvSource = mvSources.front();
		mv_rectangle_s *roi = rects.empty() ? NULL : &(rects.front());

		mv_colorspace_e colorspace = MEDIA_VISION_COLORSPACE_INVALID;

		if (mv_source_get_width(mvSource, &width) != MEDIA_VISION_ERROR_NONE ||
			mv_source_get_height(mvSource, &height) !=
					MEDIA_VISION_ERROR_NONE ||
			mv_source_get_colorspace(mvSource, &colorspace) !=
					MEDIA_VISION_ERROR_NONE ||
			mv_source_get_buffer(mvSource, &buffer, &bufferSize))
			return MEDIA_VISION_ERROR_INTERNAL;

		// TODO. Let's support various color spaces.

		if (colorspace != MEDIA_VISION_COLORSPACE_RGB888) {
			LOGE("Not Supported format!\n");
			return MEDIA_VISION_ERROR_NOT_SUPPORTED_FORMAT;
		}

		if (roi == NULL) {
			cvSource = cv::Mat(cv::Size(width, height), CV_MAKETYPE(CV_8U, 3),
							   buffer)
							   .clone();
		} else {
			cvRoi.x = roi->point.x;
			cvRoi.y = roi->point.y;
			cvRoi.width = (roi->point.x + roi->width) >= width ?
								  width - roi->point.x :
								  roi->width;
			cvRoi.height = (roi->point.y + roi->height) >= height ?
								   height - roi->point.y :
								   roi->height;
			cvSource = cv::Mat(cv::Size(width, height), CV_MAKETYPE(CV_8U, 3),
							   buffer)(cvRoi)
							   .clone();
		}

		LOGE("Size: w:%u, h:%u", cvSource.size().width, cvSource.size().height);

		if (mCh != 1 && mCh != 3) {
			LOGE("Channel not supported.");
			return MEDIA_VISION_ERROR_INVALID_PARAMETER;
		}

		std::vector<inference_engine_tensor_buffer>::iterator iter;
		for (iter = mInputTensorBuffers.begin();
			 iter != mInputTensorBuffers.end(); iter++) {
			inference_engine_tensor_buffer tensor_buffer = *iter;

			int data_type = ConvertToCv(tensor_buffer.data_type);

			// Convert color space of input tensor data and then normalize it.
			ret = Preprocess(cvSource,
							 cv::Mat(mInputSize.height, mInputSize.width,
									 data_type, tensor_buffer.buffer),
							 data_type);
			if (ret != MEDIA_VISION_ERROR_NONE) {
				LOGE("Fail to preprocess input tensor data.");
				return ret;
			}
		}

		ret = mBackend->Run(mInputTensorBuffers, mOutputTensorBuffers);

		return ConvertEngineErrorToVisionError(ret);
	}

	std::pair<std::string, bool>
	Inference::GetSupportedInferenceBackend(int backend)
	{
		return mSupportedInferenceBackend[backend];
	}

	int Inference::GetClassficationResults(
			ImageClassificationResults *classificationResults)
	{
		tensor_t outputData;

		// Get inference result and contain it to outputData.
		int ret = FillOutputResult(outputData);
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to get output result.");
			return ret;
		}

		// Will contain top N results in ascending order.
		std::vector<std::pair<float, int> > top_results;
		std::priority_queue<std::pair<float, int>,
							std::vector<std::pair<float, int> >,
							std::greater<std::pair<float, int> > >
				top_result_pq;
		float value = 0.0f;

		std::vector<std::vector<int> > inferDimInfo(outputData.dimInfo);
		std::vector<void *> inferResults(outputData.data.begin(),
										 outputData.data.end());

		int count = inferDimInfo[0][1];
		LOGI("count: %d", count);

		float *prediction = reinterpret_cast<float *>(inferResults[0]);
		for (int i = 0; i < count; ++i) {
			value = prediction[i];

			// Only add it if it beats the threshold and has a chance at being in
			// the top N.
			top_result_pq.push(std::pair<float, int>(value, i));

			// If at capacity, kick the smallest value out.
			if (top_result_pq.size() > mOutputNumbers) {
				top_result_pq.pop();
			}
		}

		// Copy to output vector and reverse into descending order.
		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());

		int classIdx = -1;
		ImageClassificationResults results;
		results.number_of_classes = 0;
		for (int idx = 0; idx < top_results.size(); ++idx) {
			if (top_results[idx].first < mThreshold)
				continue;
			LOGI("idx:%d", idx);
			LOGI("classIdx: %d", top_results[idx].second);
			LOGI("classProb: %f", top_results[idx].first);

			classIdx = top_results[idx].second;
			results.indices.push_back(classIdx);
			results.confidences.push_back(top_results[idx].first);
			results.names.push_back(mUserListName[classIdx]);
			results.number_of_classes++;
		}

		*classificationResults = results;
		LOGE("Inference: GetClassificationResults: %d\n",
			 results.number_of_classes);
		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::GetObjectDetectionResults(
			ObjectDetectionResults *detectionResults)
	{
		tensor_t outputData;

		// Get inference result and contain it to outputData.
		int ret = FillOutputResult(outputData);
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to get output result.");
			return ret;
		}

		// In case of object detection,
		// a model may apply post-process but others may not.
		// Thus, those cases should be hanlded separately.
		std::vector<std::vector<int> > inferDimInfo(outputData.dimInfo);
		LOGI("inferDimInfo size: %zu", outputData.dimInfo.size());

		std::vector<void *> inferResults(outputData.data.begin(),
										 outputData.data.end());
		LOGI("inferResults size: %zu", inferResults.size());

		float *boxes = nullptr;
		float *classes = nullptr;
		float *scores = nullptr;
		int number_of_detections = 0;

		cv::Mat cvScores, cvClasses, cvBoxes;
		if (outputData.dimInfo.size() == 1) {
			// there is no way to know how many objects are detect unless the number of objects aren't
			// provided. In the case, each backend should provide the number of results manually.
			// For example, in OpenCV, MobilenetV1-SSD doesn't provide it so the number of objects are
			// written to the 1st element i.e., outputData.data[0] (the shape is 1x1xNx7 and the 1st of 7
			// indicats the image id. But it is useless if a batch mode isn't supported.
			// So, use the 1st of 7.

			number_of_detections = static_cast<int>(
					*reinterpret_cast<float *>(outputData.data[0]));
			cv::Mat cvOutputData(number_of_detections, inferDimInfo[0][3],
								 CV_32F, outputData.data[0]);

			// boxes
			cv::Mat cvLeft = cvOutputData.col(3).clone();
			cv::Mat cvTop = cvOutputData.col(4).clone();
			cv::Mat cvRight = cvOutputData.col(5).clone();
			cv::Mat cvBottom = cvOutputData.col(6).clone();

			cv::Mat cvBoxElems[] = { cvTop, cvLeft, cvBottom, cvRight };
			cv::hconcat(cvBoxElems, 4, cvBoxes);

			// classes
			cvClasses = cvOutputData.col(1).clone();

			// scores
			cvScores = cvOutputData.col(2).clone();

			boxes = cvBoxes.ptr<float>(0);
			classes = cvClasses.ptr<float>(0);
			scores = cvScores.ptr<float>(0);

		} else {
			boxes = reinterpret_cast<float *>(inferResults[0]);
			classes = reinterpret_cast<float *>(inferResults[1]);
			scores = reinterpret_cast<float *>(inferResults[2]);
			number_of_detections =
					(int) (*reinterpret_cast<float *>(inferResults[3]));
		}

		LOGI("number_of_detections = %d", number_of_detections);

		int left, top, right, bottom;
		cv::Rect loc;

		ObjectDetectionResults results;
		results.number_of_objects = 0;
		for (int idx = 0; idx < number_of_detections; ++idx) {
			if (scores[idx] < mThreshold)
				continue;

			left = static_cast<int>(boxes[idx * 4 + 1] * mSourceSize.width);
			top = static_cast<int>(boxes[idx * 4 + 0] * mSourceSize.height);
			right = static_cast<int>(boxes[idx * 4 + 3] * mSourceSize.width);
			bottom = static_cast<int>(boxes[idx * 4 + 2] * mSourceSize.height);

			loc.x = left;
			loc.y = top;
			loc.width = right - left + 1;
			loc.height = bottom - top + 1;

			results.indices.push_back(static_cast<int>(classes[idx]));
			results.confidences.push_back(scores[idx]);
			results.names.push_back(
					mUserListName[static_cast<int>(classes[idx])]);
			results.locations.push_back(loc);
			results.number_of_objects++;

			LOGI("objectClass: %d", static_cast<int>(classes[idx]));
			LOGI("confidence:%f", scores[idx]);
			LOGI("left:%d, top:%d, right:%d, bottom:%d", left, top, right,
				 bottom);
		}

		*detectionResults = results;
		LOGE("Inference: GetObjectDetectionResults: %d\n",
			 results.number_of_objects);
		return MEDIA_VISION_ERROR_NONE;
	}

	int
	Inference::GetFaceDetectionResults(FaceDetectionResults *detectionResults)
	{
		tensor_t outputData;

		// Get inference result and contain it to outputData.
		int ret = FillOutputResult(outputData);
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to get output result.");
			return ret;
		}

		// In case of object detection,
		// a model may apply post-process but others may not.
		// Thus, those cases should be hanlded separately.
		std::vector<std::vector<int> > inferDimInfo(outputData.dimInfo);
		LOGI("inferDimInfo size: %zu", outputData.dimInfo.size());

		std::vector<void *> inferResults(outputData.data.begin(),
										 outputData.data.end());
		LOGI("inferResults size: %zu", inferResults.size());

		float *boxes = nullptr;
		float *classes = nullptr;
		float *scores = nullptr;
		int number_of_detections = 0;

		cv::Mat cvScores, cvClasses, cvBoxes;
		if (outputData.dimInfo.size() == 1) {
			// there is no way to know how many objects are detect unless the number of objects aren't
			// provided. In the case, each backend should provide the number of results manually.
			// For example, in OpenCV, MobilenetV1-SSD doesn't provide it so the number of objects are
			// written to the 1st element i.e., outputData.data[0] (the shape is 1x1xNx7 and the 1st of 7
			// indicats the image id. But it is useless if a batch mode isn't supported.
			// So, use the 1st of 7.

			number_of_detections = static_cast<int>(
					*reinterpret_cast<float *>(outputData.data[0]));
			cv::Mat cvOutputData(number_of_detections, inferDimInfo[0][3],
								 CV_32F, outputData.data[0]);

			// boxes
			cv::Mat cvLeft = cvOutputData.col(3).clone();
			cv::Mat cvTop = cvOutputData.col(4).clone();
			cv::Mat cvRight = cvOutputData.col(5).clone();
			cv::Mat cvBottom = cvOutputData.col(6).clone();

			cv::Mat cvBoxElems[] = { cvTop, cvLeft, cvBottom, cvRight };
			cv::hconcat(cvBoxElems, 4, cvBoxes);

			// classes
			cvClasses = cvOutputData.col(1).clone();

			// scores
			cvScores = cvOutputData.col(2).clone();

			boxes = cvBoxes.ptr<float>(0);
			classes = cvClasses.ptr<float>(0);
			scores = cvScores.ptr<float>(0);

		} else {
			boxes = reinterpret_cast<float *>(inferResults[0]);
			classes = reinterpret_cast<float *>(inferResults[1]);
			scores = reinterpret_cast<float *>(inferResults[2]);
			number_of_detections = static_cast<int>(
					*reinterpret_cast<float *>(inferResults[3]));
		}

		int left, top, right, bottom;
		cv::Rect loc;

		FaceDetectionResults results;
		results.number_of_faces = 0;
		for (int idx = 0; idx < number_of_detections; ++idx) {
			if (scores[idx] < mThreshold)
				continue;

			left = static_cast<int>(boxes[idx * 4 + 1] * mSourceSize.width);
			top = static_cast<int>(boxes[idx * 4 + 0] * mSourceSize.height);
			right = static_cast<int>(boxes[idx * 4 + 3] * mSourceSize.width);
			bottom = static_cast<int>(boxes[idx * 4 + 2] * mSourceSize.height);

			loc.x = left;
			loc.y = top;
			loc.width = right - left + 1;
			loc.height = bottom - top + 1;

			results.confidences.push_back(scores[idx]);
			results.locations.push_back(loc);
			results.number_of_faces++;

			LOGI("confidence:%f", scores[idx]);
			LOGI("class: %f", classes[idx]);
			LOGI("left:%f, top:%f, right:%f, bottom:%f", boxes[idx * 4 + 1],
				 boxes[idx * 4 + 0], boxes[idx * 4 + 3], boxes[idx * 4 + 2]);
			LOGI("left:%d, top:%d, right:%d, bottom:%d", left, top, right,
				 bottom);
		}

		*detectionResults = results;
		LOGE("Inference: GetFaceDetectionResults: %d\n",
			 results.number_of_faces);
		return MEDIA_VISION_ERROR_NONE;
	}

	int Inference::GetFacialLandMarkDetectionResults(
			FacialLandMarkDetectionResults *detectionResults)
	{
		tensor_t outputData;

		// Get inference result and contain it to outputData.
		int ret = FillOutputResult(outputData);
		if (ret != MEDIA_VISION_ERROR_NONE) {
			LOGE("Fail to get output result.");
			return ret;
		}

		std::vector<std::vector<int> > inferDimInfo(outputData.dimInfo);
		std::vector<void *> inferResults(outputData.data.begin(),
										 outputData.data.end());

		long number_of_detections = inferDimInfo[0][1];
		float *loc = reinterpret_cast<float *>(inferResults[0]);

		FacialLandMarkDetectionResults results;
		results.number_of_landmarks = 0;

		cv::Point point(0, 0);
		results.number_of_landmarks = 0;
		LOGI("imgW:%d, imgH:%d", mSourceSize.width, mSourceSize.height);
		for (int idx = 0; idx < number_of_detections; idx += 2) {
			point.x = static_cast<int>(loc[idx] * mSourceSize.width);
			point.y = static_cast<int>(loc[idx + 1] * mSourceSize.height);

			results.locations.push_back(point);
			results.number_of_landmarks++;

			LOGI("x:%d, y:%d", point.x, point.y);
		}

		*detectionResults = results;
		LOGE("Inference: FacialLandmarkDetectionResults: %d\n",
			 results.number_of_landmarks);
		return MEDIA_VISION_ERROR_NONE;
	}

} /* Inference */
} /* MediaVision */