mv_machine_learning: convert ImageClassification class into template class
[platform/core/api/mediavision.git] / mv_machine_learning / image_classification / src / image_classification_default.cpp
1 /**
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <string.h>
18 #include <map>
19 #include <algorithm>
20
21 #include "machine_learning_exception.h"
22 #include "image_classification_default.h"
23 #include "Postprocess.h"
24
25 using namespace std;
26 using namespace mediavision::inference;
27 using namespace mediavision::machine_learning::exception;
28
29 namespace mediavision
30 {
31 namespace machine_learning
32 {
33 template<typename T>
34 ImageClassificationDefault<T>::ImageClassificationDefault(shared_ptr<MachineLearningConfig> config)
35                 : ImageClassification<T>(config), _result()
36 {}
37
38 template<typename T> ImageClassificationDefault<T>::~ImageClassificationDefault()
39 {}
40
41 template<typename T> ImageClassificationResult &ImageClassificationDefault<T>::result()
42 {
43         vector<string> names;
44
45         ImageClassification<T>::getOutputNames(names);
46
47         vector<float> output_vec;
48
49         // In case of image classification model, only one output tensor is used.
50         ImageClassification<T>::getOutpuTensor(names[0], output_vec);
51
52         auto metaInfo = _config->getOutputMetaMap().at(names[0]);
53         auto decodingScore = static_pointer_cast<DecodingScore>(metaInfo->decodingTypeMap.at(DecodingType::SCORE));
54
55         if (decodingScore->type == ScoreType::SIGMOID) {
56                 for (size_t idx = 0; idx < output_vec.size(); ++idx)
57                         output_vec[idx] = PostProcess::sigmoid(output_vec[idx]);
58         }
59
60         _result.label = _labels[max_element(output_vec.begin(), output_vec.end()) - output_vec.begin()];
61         LOGI("Label = %s", _result.label.c_str());
62
63         return _result;
64 }
65
66 template class ImageClassificationDefault<unsigned char>;
67 template class ImageClassificationDefault<float>;
68
69 }
70 }