• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_IMPL_H_
17 #define TENSORFLOW_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_IMPL_H_
18 
19 #include <algorithm>
20 #include <queue>
21 
22 namespace tflite {
23 namespace label_image {
24 
25 extern bool input_floating;
26 
27 // Returns the top N confidence values over threshold in the provided vector,
28 // sorted by confidence in descending order.
29 template <class T>
get_top_n(T * prediction,int prediction_size,size_t num_results,float threshold,std::vector<std::pair<float,int>> * top_results,bool input_floating)30 void get_top_n(T* prediction, int prediction_size, size_t num_results,
31                float threshold, std::vector<std::pair<float, int>>* top_results,
32                bool input_floating) {
33   // Will contain top N results in ascending order.
34   std::priority_queue<std::pair<float, int>, std::vector<std::pair<float, int>>,
35                       std::greater<std::pair<float, int>>>
36       top_result_pq;
37 
38   const long count = prediction_size;  // NOLINT(runtime/int)
39   for (int i = 0; i < count; ++i) {
40     float value;
41     if (input_floating)
42       value = prediction[i];
43     else
44       value = prediction[i] / 255.0;
45     // Only add it if it beats the threshold and has a chance at being in
46     // the top N.
47     if (value < threshold) {
48       continue;
49     }
50 
51     top_result_pq.push(std::pair<float, int>(value, i));
52 
53     // If at capacity, kick the smallest value out.
54     if (top_result_pq.size() > num_results) {
55       top_result_pq.pop();
56     }
57   }
58 
59   // Copy to output vector and reverse into descending order.
60   while (!top_result_pq.empty()) {
61     top_results->push_back(top_result_pq.top());
62     top_result_pq.pop();
63   }
64   std::reverse(top_results->begin(), top_results->end());
65 }
66 
67 }  // namespace label_image
68 }  // namespace tflite
69 
70 #endif  // TENSORFLOW_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_IMPL_H_
71