blob: 61005ab5fdaf1701f48fbb4cc01fe32e8fe4dd62 [file] [log] [blame]
Isabella Gottardi05e56442018-11-16 11:26:52 +00001/*
2 * Copyright (c) 2018 ARM Limited.
3 *
4 * SPDX-License-Identifier: MIT
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24#include "arm_compute/runtime/CPP/functions/CPPDetectionOutputLayer.h"
25
26#include "arm_compute/core/Error.h"
27#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/Validate.h"
29#include "support/ToolchainSupport.h"
30
31#include <list>
32
33namespace arm_compute
34{
35namespace
36{
37Status validate_arguments(const ITensorInfo *input_loc, const ITensorInfo *input_conf, const ITensorInfo *input_priorbox, const ITensorInfo *output, DetectionOutputLayerInfo info)
38{
39 ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(input_loc, input_conf, input_priorbox, output);
40 ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input_loc, 1, DataType::F32);
41 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_loc, input_conf, input_priorbox);
42 ARM_COMPUTE_RETURN_ERROR_ON_MSG(input_loc->num_dimensions() > 2, "The location input tensor should be [C1, N].");
43 ARM_COMPUTE_RETURN_ERROR_ON_MSG(input_conf->num_dimensions() > 2, "The location input tensor should be [C2, N].");
44 ARM_COMPUTE_RETURN_ERROR_ON_MSG(input_priorbox->num_dimensions() > 3, "The priorbox input tensor should be [C3, 2, N].");
45
46 ARM_COMPUTE_RETURN_ERROR_ON_MSG(info.eta() <= 0.f && info.eta() > 1.f, "Eta should be between 0 and 1");
47
48 const int num_priors = input_priorbox->tensor_shape()[0] / 4;
49 ARM_COMPUTE_RETURN_ERROR_ON_MSG(static_cast<size_t>((num_priors * info.num_loc_classes() * 4)) != input_loc->tensor_shape()[0], "Number of priors must match number of location predictions.");
50 ARM_COMPUTE_RETURN_ERROR_ON_MSG(static_cast<size_t>((num_priors * info.num_classes())) != input_conf->tensor_shape()[0], "Number of priors must match number of confidence predictions.");
51
52 // Validate configured output
53 if(output->total_size() != 0)
54 {
55 const unsigned int max_size = info.keep_top_k() * (input_loc->num_dimensions() > 1 ? input_loc->dimension(1) : 1);
56 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(output->tensor_shape(), TensorShape(7U, max_size));
57 ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input_loc, output);
58 }
59
60 return Status{};
61}
62
63/** Function used to sort pair<float, T> in descend order based on the score (first) value.
64 */
65template <typename T>
66bool SortScorePairDescend(const std::pair<float, T> &pair1,
67 const std::pair<float, T> &pair2)
68{
69 return pair1.first > pair2.first;
70}
71
72/** Get location predictions from input_loc.
73 *
74 * @param[in] input_loc The input location prediction.
75 * @param[in] num The number of images.
76 * @param[in] num_priors number of predictions per class.
77 * @param[in] num_loc_classes number of location classes. It is 1 if share_location is true,
78 * and is equal to number of classes needed to predict otherwise.
79 * @param[in] share_location If true, all classes share the same location prediction.
80 * @param[out] all_location_predictions All the location predictions.
81 *
82 */
83void retrieve_all_loc_predictions(const ITensor *input_loc, const int num,
84 const int num_priors, const int num_loc_classes,
85 const bool share_location, std::vector<LabelBBox> &all_location_predictions)
86{
87 for(int i = 0; i < num; ++i)
88 {
89 for(int c = 0; c < num_loc_classes; ++c)
90 {
91 int label = share_location ? -1 : c;
92 if(all_location_predictions[i].find(label) == all_location_predictions[i].end())
93 {
94 all_location_predictions[i][label].resize(num_priors);
95 }
96 else
97 {
98 ARM_COMPUTE_ERROR_ON(all_location_predictions[i][label].size() != static_cast<size_t>(num_priors));
99 break;
100 }
101 }
102 }
103 for(int i = 0; i < num; ++i)
104 {
105 for(int p = 0; p < num_priors; ++p)
106 {
107 for(int c = 0; c < num_loc_classes; ++c)
108 {
109 const int label = share_location ? -1 : c;
110 const int base_ptr = i * num_priors * num_loc_classes * 4 + p * num_loc_classes * 4 + c * 4;
111 //xmin, ymin, xmax, ymax
112 all_location_predictions[i][label][p][0] = *reinterpret_cast<float *>(input_loc->ptr_to_element(Coordinates(base_ptr)));
113 all_location_predictions[i][label][p][1] = *reinterpret_cast<float *>(input_loc->ptr_to_element(Coordinates(base_ptr + 1)));
114 all_location_predictions[i][label][p][2] = *reinterpret_cast<float *>(input_loc->ptr_to_element(Coordinates(base_ptr + 2)));
115 all_location_predictions[i][label][p][3] = *reinterpret_cast<float *>(input_loc->ptr_to_element(Coordinates(base_ptr + 3)));
116 }
117 }
118 }
119}
120
121/** Get confidence predictions from input_conf.
122 *
123 * @param[in] input_loc The input location prediction.
124 * @param[in] num The number of images.
125 * @param[in] num_priors Number of predictions per class.
126 * @param[in] num_loc_classes Number of location classes. It is 1 if share_location is true,
127 * and is equal to number of classes needed to predict otherwise.
128 * @param[out] all_location_predictions All the location predictions.
129 *
130 */
131void retrieve_all_conf_scores(const ITensor *input_conf, const int num,
132 const int num_priors, const int num_classes,
133 std::vector<std::map<int, std::vector<float>>> &all_confidence_scores)
134{
135 std::vector<float> tmp_buffer;
136 tmp_buffer.resize(num * num_priors * num_classes);
137 for(int i = 0; i < num; ++i)
138 {
139 for(int c = 0; c < num_classes; ++c)
140 {
141 for(int p = 0; p < num_priors; ++p)
142 {
143 tmp_buffer[i * num_classes * num_priors + c * num_priors + p] =
144 *reinterpret_cast<float *>(input_conf->ptr_to_element(Coordinates(i * num_classes * num_priors + p * num_classes + c)));
145 }
146 }
147 }
148 for(int i = 0; i < num; ++i)
149 {
150 for(int c = 0; c < num_classes; ++c)
151 {
152 all_confidence_scores[i][c].resize(num_priors);
153 all_confidence_scores[i][c].assign(&tmp_buffer[i * num_classes * num_priors + c * num_priors],
154 &tmp_buffer[i * num_classes * num_priors + c * num_priors + num_priors]);
155 }
156 }
157}
158
159/** Get prior boxes from input_priorbox.
160 *
161 * @param[in] input_priorbox The input location prediction.
162 * @param[in] num_priors Number of priors.
163 * @param[in] num_loc_classes number of location classes. It is 1 if share_location is true,
164 * and is equal to number of classes needed to predict otherwise.
165 * @param[out] all_prior_bboxes If true, all classes share the same location prediction.
166 * @param[out] all_location_predictions All the location predictions.
167 *
168 */
169void retrieve_all_priorbox(const ITensor *input_priorbox,
170 const int num_priors,
171 std::vector<NormalizedBBox> &all_prior_bboxes,
172 std::vector<std::array<float, 4>> &all_prior_variances)
173{
174 for(int i = 0; i < num_priors; ++i)
175 {
176 all_prior_bboxes[i] = { *reinterpret_cast<float *>(input_priorbox->ptr_to_element(Coordinates(i * 4))),
177 *reinterpret_cast<float *>(input_priorbox->ptr_to_element(Coordinates(i * 4 + 1))),
178 *reinterpret_cast<float *>(input_priorbox->ptr_to_element(Coordinates(i * 4 + 2))),
179 *reinterpret_cast<float *>(input_priorbox->ptr_to_element(Coordinates(i * 4 + 3)))
180 };
181 }
182
183 std::array<float, 4> var({ 0, 0, 0, 0 });
184 for(int i = 0; i < num_priors; ++i)
185 {
186 for(int j = 0; j < 4; ++j)
187 {
188 var[j] = *reinterpret_cast<float *>(input_priorbox->ptr_to_element(Coordinates((num_priors + i) * 4 + j)));
189 }
190 all_prior_variances[i] = var;
191 }
192}
193
194/** Decode a bbox according to a prior bbox.
195 *
196 * @param[in] prior_bbox The input prior bounding boxes.
197 * @param[in] prior_variance The corresponding input variance.
198 * @param[in] code_type The detection output code type used to decode the results.
199 * @param[in] variance_encoded_in_target If true, the variance is encoded in target.
200 * @param[in] clip_bbox If true, the results should be between 0.f and 1.f.
201 * @param[in] bbox The input bbox to decode
202 * @param[out] decode_bbox The decoded bboxes.
203 *
204 */
205void DecodeBBox(const NormalizedBBox &prior_bbox, const std::array<float, 4> &prior_variance,
206 const DetectionOutputLayerCodeType code_type, const bool variance_encoded_in_target,
207 const bool clip_bbox, const NormalizedBBox &bbox, NormalizedBBox &decode_bbox)
208{
209 // if the variance is encoded in target, we simply need to add the offset predictions
210 // otherwise we need to scale the offset accordingly.
211 switch(code_type)
212 {
213 case DetectionOutputLayerCodeType::CORNER:
214 {
215 decode_bbox[0] = prior_bbox[0] + (variance_encoded_in_target ? bbox[0] : prior_variance[0] * bbox[0]);
216 decode_bbox[1] = prior_bbox[1] + (variance_encoded_in_target ? bbox[1] : prior_variance[1] * bbox[1]);
217 decode_bbox[2] = prior_bbox[2] + (variance_encoded_in_target ? bbox[2] : prior_variance[2] * bbox[2]);
218 decode_bbox[3] = prior_bbox[3] + (variance_encoded_in_target ? bbox[3] : prior_variance[3] * bbox[3]);
219
220 break;
221 }
222 case DetectionOutputLayerCodeType::CENTER_SIZE:
223 {
224 const float prior_width = prior_bbox[2] - prior_bbox[0];
225 const float prior_height = prior_bbox[3] - prior_bbox[1];
226
227 // Check if the prior width and height are right
228 ARM_COMPUTE_ERROR_ON(prior_width <= 0.f);
229 ARM_COMPUTE_ERROR_ON(prior_height <= 0.f);
230
231 const float prior_center_x = (prior_bbox[0] + prior_bbox[2]) / 2.;
232 const float prior_center_y = (prior_bbox[1] + prior_bbox[3]) / 2.;
233
234 const float decode_bbox_center_x = (variance_encoded_in_target ? bbox[0] : prior_variance[0] * bbox[0]) * prior_width + prior_center_x;
235 const float decode_bbox_center_y = (variance_encoded_in_target ? bbox[1] : prior_variance[1] * bbox[1]) * prior_height + prior_center_y;
236 const float decode_bbox_width = (variance_encoded_in_target ? std::exp(bbox[2]) : std::exp(prior_variance[2] * bbox[2])) * prior_width;
237 const float decode_bbox_height = (variance_encoded_in_target ? std::exp(bbox[3]) : std::exp(prior_variance[3] * bbox[3])) * prior_height;
238
239 decode_bbox[0] = (decode_bbox_center_x - decode_bbox_width / 2.f);
240 decode_bbox[1] = (decode_bbox_center_y - decode_bbox_height / 2.f);
241 decode_bbox[2] = (decode_bbox_center_x + decode_bbox_width / 2.f);
242 decode_bbox[3] = (decode_bbox_center_y + decode_bbox_height / 2.f);
243
244 break;
245 }
246 case DetectionOutputLayerCodeType::CORNER_SIZE:
247 {
248 const float prior_width = prior_bbox[2] - prior_bbox[0];
249 const float prior_height = prior_bbox[3] - prior_bbox[1];
250
251 // Check if the prior width and height are greater than 0
252 ARM_COMPUTE_ERROR_ON(prior_width <= 0.f);
253 ARM_COMPUTE_ERROR_ON(prior_height <= 0.f);
254
255 decode_bbox[0] = prior_bbox[0] + (variance_encoded_in_target ? bbox[0] : prior_variance[0] * bbox[0]) * prior_width;
256 decode_bbox[1] = prior_bbox[1] + (variance_encoded_in_target ? bbox[1] : prior_variance[1] * bbox[1]) * prior_height;
257 decode_bbox[2] = prior_bbox[2] + (variance_encoded_in_target ? bbox[2] : prior_variance[2] * bbox[2]) * prior_width;
258 decode_bbox[3] = prior_bbox[3] + (variance_encoded_in_target ? bbox[3] : prior_variance[3] * bbox[3]) * prior_height;
259
260 break;
261 }
262 default:
263 ARM_COMPUTE_ERROR("Unsupported Detection Output Code Type.");
264 }
265
266 if(clip_bbox)
267 {
268 for(auto &d_bbox : decode_bbox)
269 {
270 d_bbox = utility::clamp(d_bbox, 0.f, 1.f);
271 }
272 }
273}
274
275/** Do non maximum suppression given bboxes and scores.
276 *
277 * @param[in] bboxes The input bounding boxes.
278 * @param[in] scores The corresponding input confidence.
279 * @param[in] score_threshold The threshold used to filter detection results.
280 * @param[in] nms_threshold The threshold used in non maximum suppression.
281 * @param[in] eta Adaptation rate for nms threshold.
282 * @param[in] top_k If not -1, keep at most top_k picked indices.
283 * @param[out] indices The kept indices of bboxes after nms.
284 *
285 */
286void ApplyNMSFast(const std::vector<NormalizedBBox> &bboxes,
287 const std::vector<float> &scores, const float score_threshold,
288 const float nms_threshold, const float eta, const int top_k,
289 std::vector<int> &indices)
290{
291 ARM_COMPUTE_ERROR_ON_MSG(bboxes.size() != scores.size(), "bboxes and scores have different size.");
292
293 // Get top_k scores (with corresponding indices).
294 std::list<std::pair<float, int>> score_index_vec;
295
296 // Generate index score pairs.
297 for(size_t i = 0; i < scores.size(); ++i)
298 {
299 if(scores[i] > score_threshold)
300 {
301 score_index_vec.emplace_back(std::make_pair(scores[i], i));
302 }
303 }
304
305 // Sort the score pair according to the scores in descending order
306 score_index_vec.sort(SortScorePairDescend<int>);
307
308 // Keep top_k scores if needed.
309 const int score_index_vec_size = score_index_vec.size();
310 if(top_k > -1 && top_k < score_index_vec_size)
311 {
312 score_index_vec.resize(top_k);
313 }
314
315 // Do nms.
316 float adaptive_threshold = nms_threshold;
317 indices.clear();
318
319 while(!score_index_vec.empty())
320 {
321 const int idx = score_index_vec.front().second;
322 bool keep = true;
323 for(int kept_idx : indices)
324 {
325 if(keep)
326 {
327 // Compute the jaccard (intersection over union IoU) overlap between two bboxes.
328 NormalizedBBox intersect_bbox = std::array<float, 4>({ 0, 0, 0, 0 });
329 if(bboxes[kept_idx][0] > bboxes[idx][2] || bboxes[kept_idx][2] < bboxes[idx][0] || bboxes[kept_idx][1] > bboxes[idx][3] || bboxes[kept_idx][3] < bboxes[idx][1])
330 {
331 intersect_bbox = std::array<float, 4>({ 0, 0, 0, 0 });
332 }
333 else
334 {
335 intersect_bbox = std::array<float, 4>({ std::max(bboxes[idx][0], bboxes[kept_idx][0]), std::max(bboxes[idx][1], bboxes[kept_idx][1]), std::min(bboxes[idx][2], bboxes[kept_idx][2]), std::min(bboxes[idx][3],
336 bboxes[kept_idx][3])
337 });
338 }
339
340 float intersect_width = intersect_bbox[2] - intersect_bbox[0];
341 float intersect_height = intersect_bbox[3] - intersect_bbox[1];
342
343 float overlap = 0.f;
344 if(intersect_width > 0 && intersect_height > 0)
345 {
346 float intersect_size = intersect_width * intersect_height;
347 float bbox1_size = (bboxes[idx][2] < bboxes[idx][0]
348 || bboxes[idx][3] < bboxes[idx][1]) ?
349 0.f :
350 (bboxes[idx][2] - bboxes[idx][0]) * (bboxes[idx][3] - bboxes[idx][1]); //BBoxSize(bboxes[idx]);
351 float bbox2_size = (bboxes[kept_idx][2] < bboxes[kept_idx][0]
352 || bboxes[kept_idx][3] < bboxes[kept_idx][1]) ?
353 0.f :
354 (bboxes[kept_idx][2] - bboxes[kept_idx][0]) * (bboxes[kept_idx][3] - bboxes[kept_idx][1]); // BBoxSize(bboxes[kept_idx]);
355 overlap = intersect_size / (bbox1_size + bbox2_size - intersect_size);
356 }
357 keep = (overlap <= adaptive_threshold);
358 }
359 else
360 {
361 break;
362 }
363 }
364 if(keep)
365 {
366 indices.push_back(idx);
367 }
368 score_index_vec.erase(score_index_vec.begin());
369 if(keep && eta < 1 && adaptive_threshold > 0.5)
370 {
371 adaptive_threshold *= eta;
372 }
373 }
374}
375} // namespace
376
377CPPDetectionOutputLayer::CPPDetectionOutputLayer()
378 : _input_loc(nullptr), _input_conf(nullptr), _input_priorbox(nullptr), _output(nullptr), _info(), _num_priors(), _num(), _all_location_predictions(), _all_confidence_scores(), _all_prior_bboxes(),
379 _all_prior_variances(), _all_decode_bboxes(), _all_indices()
380{
381}
382
383void CPPDetectionOutputLayer::configure(const ITensor *input_loc, const ITensor *input_conf, const ITensor *input_priorbox, ITensor *output, DetectionOutputLayerInfo info)
384{
385 ARM_COMPUTE_ERROR_ON_NULLPTR(input_loc, input_conf, input_priorbox, output);
386 // Output auto initialization if not yet initialized
387 // Since the number of bboxes to kept is unknown before nms, the shape is set to the maximum
388 // The maximum is keep_top_k * input_loc_size[1]
389 // Each row is a 7 dimension std::vector, which stores [image_id, label, confidence, xmin, ymin, xmax, ymax]
390 const unsigned int max_size = info.keep_top_k() * (input_loc->info()->num_dimensions() > 1 ? input_loc->info()->dimension(1) : 1);
391 auto_init_if_empty(*output->info(), input_loc->info()->clone()->set_tensor_shape(TensorShape(7U, max_size)));
392
393 // Perform validation step
394 ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(input_loc->info(), input_conf->info(), input_priorbox->info(), output->info(), info));
395
396 _input_loc = input_loc;
397 _input_conf = input_conf;
398 _input_priorbox = input_priorbox;
399 _output = output;
400 _info = info;
401 _num_priors = input_priorbox->info()->dimension(0) / 4;
402 _num = (_input_loc->info()->num_dimensions() > 1 ? _input_loc->info()->dimension(1) : 1);
403
404 _all_location_predictions.resize(_num);
405 _all_confidence_scores.resize(_num);
406 _all_prior_bboxes.resize(_num_priors);
407 _all_prior_variances.resize(_num_priors);
408 _all_decode_bboxes.resize(_num);
409
410 for(int i = 0; i < _num; ++i)
411 {
412 for(int c = 0; c < _info.num_loc_classes(); ++c)
413 {
414 const int label = _info.share_location() ? -1 : c;
415 if(label == _info.background_label_id())
416 {
417 // Ignore background class.
418 continue;
419 }
420 _all_decode_bboxes[i][label].resize(_num_priors);
421 }
422 }
423 _all_indices.resize(_num);
424
425 Coordinates coord;
426 coord.set_num_dimensions(output->info()->num_dimensions());
427 output->info()->set_valid_region(ValidRegion(coord, output->info()->tensor_shape()));
428}
429
430Status CPPDetectionOutputLayer::validate(const ITensorInfo *input_loc, const ITensorInfo *input_conf, const ITensorInfo *input_priorbox, const ITensorInfo *output, DetectionOutputLayerInfo info)
431{
432 ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input_loc, input_conf, input_priorbox, output, info));
433 return Status{};
434}
435
436void CPPDetectionOutputLayer::run()
437{
438 // Retrieve all location predictions.
439 retrieve_all_loc_predictions(_input_loc, _num, _num_priors, _info.num_loc_classes(), _info.share_location(), _all_location_predictions);
440
441 // Retrieve all confidences.
442 retrieve_all_conf_scores(_input_conf, _num, _num_priors, _info.num_classes(), _all_confidence_scores);
443
444 // Retrieve all prior bboxes.
445 retrieve_all_priorbox(_input_priorbox, _num_priors, _all_prior_bboxes, _all_prior_variances);
446
447 // Decode all loc predictions to bboxes
448 const bool clip_bbox = false;
449 for(int i = 0; i < _num; ++i)
450 {
451 for(int c = 0; c < _info.num_loc_classes(); ++c)
452 {
453 const int label = _info.share_location() ? -1 : c;
454 if(label == _info.background_label_id())
455 {
456 // Ignore background class.
457 continue;
458 }
459 ARM_COMPUTE_ERROR_ON_MSG(_all_location_predictions[i].find(label) == _all_location_predictions[i].end(), "Could not find location predictions for label %d.", label);
460
461 const std::vector<NormalizedBBox> &label_loc_preds = _all_location_predictions[i].find(label)->second;
462
463 const int num_bboxes = _all_prior_bboxes.size();
464 ARM_COMPUTE_ERROR_ON(_all_prior_variances[i].size() != 4);
465
466 for(int j = 0; j < num_bboxes; ++j)
467 {
468 DecodeBBox(_all_prior_bboxes[j], _all_prior_variances[j], _info.code_type(), _info.variance_encoded_in_target(), clip_bbox, label_loc_preds[j], _all_decode_bboxes[i][label][j]);
469 }
470 }
471 }
472
473 int num_kept = 0;
474
475 for(int i = 0; i < _num; ++i)
476 {
477 const LabelBBox &decode_bboxes = _all_decode_bboxes[i];
478 const std::map<int, std::vector<float>> &conf_scores = _all_confidence_scores[i];
479
480 std::map<int, std::vector<int>> indices;
481 int num_det = 0;
482 for(int c = 0; c < _info.num_classes(); ++c)
483 {
484 if(c == _info.background_label_id())
485 {
486 // Ignore background class
487 continue;
488 }
489 const int label = _info.share_location() ? -1 : c;
490 if(conf_scores.find(c) == conf_scores.end() || decode_bboxes.find(label) == decode_bboxes.end())
491 {
492 ARM_COMPUTE_ERROR("Could not find predictions for label %d.", label);
493 }
494 const std::vector<float> &scores = conf_scores.find(c)->second;
495 const std::vector<NormalizedBBox> &bboxes = decode_bboxes.find(label)->second;
496
497 ApplyNMSFast(bboxes, scores, _info.confidence_threshold(), _info.nms_threshold(), _info.eta(), _info.top_k(), indices[c]);
498
499 num_det += indices[c].size();
500 }
501
502 int num_to_add = 0;
503 if(_info.keep_top_k() > -1 && num_det > _info.keep_top_k())
504 {
505 std::vector<std::pair<float, std::pair<int, int>>> score_index_pairs;
506 for(auto it : indices)
507 {
508 const int label = it.first;
509 const std::vector<int> &label_indices = it.second;
510
511 if(conf_scores.find(label) == conf_scores.end())
512 {
513 ARM_COMPUTE_ERROR("Could not find predictions for label %d.", label);
514 }
515
516 const std::vector<float> &scores = conf_scores.find(label)->second;
517 for(auto idx : label_indices)
518 {
519 ARM_COMPUTE_ERROR_ON(idx > static_cast<int>(scores.size()));
520 score_index_pairs.push_back(std::make_pair(scores[idx], std::make_pair(label, idx)));
521 }
522 }
523
524 // Keep top k results per image.
525 std::sort(score_index_pairs.begin(), score_index_pairs.end(), SortScorePairDescend<std::pair<int, int>>);
526 score_index_pairs.resize(_info.keep_top_k());
527
528 // Store the new indices.
529
530 std::map<int, std::vector<int>> new_indices;
531 for(auto score_index_pair : score_index_pairs)
532 {
533 int label = score_index_pair.second.first;
534 int idx = score_index_pair.second.second;
535 new_indices[label].push_back(idx);
536 }
537 _all_indices[i] = new_indices;
538 num_to_add = _info.keep_top_k();
539 }
540 else
541 {
542 _all_indices[i] = indices;
543 num_to_add = num_det;
544 }
545 num_kept += num_to_add;
546 }
547
548 //Update the valid region of the ouput to mark the exact number of detection
549 _output->info()->set_valid_region(ValidRegion(Coordinates(0, 0), TensorShape(7, num_kept)));
550
551 int count = 0;
552 for(int i = 0; i < _num; ++i)
553 {
554 const std::map<int, std::vector<float>> &conf_scores = _all_confidence_scores[i];
555 const LabelBBox &decode_bboxes = _all_decode_bboxes[i];
556 for(auto &it : _all_indices[i])
557 {
558 const int label = it.first;
559 const std::vector<float> &scores = conf_scores.find(label)->second;
560 const int loc_label = _info.share_location() ? -1 : label;
561 if(conf_scores.find(label) == conf_scores.end() || decode_bboxes.find(loc_label) == decode_bboxes.end())
562 {
563 // Either if there are no confidence predictions
564 // or there are no location predictions for current label.
565 ARM_COMPUTE_ERROR("Could not find predictions for the label %d.", label);
566 }
567 const std::vector<NormalizedBBox> &bboxes = decode_bboxes.find(loc_label)->second;
568 const std::vector<int> &indices = it.second;
569
570 for(auto idx : indices)
571 {
572 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7)))) = i;
573 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 1)))) = label;
574 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 2)))) = scores[idx];
575 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 3)))) = bboxes[idx][0];
576 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 4)))) = bboxes[idx][1];
577 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 5)))) = bboxes[idx][2];
578 *(reinterpret_cast<float *>(_output->ptr_to_element(Coordinates(count * 7 + 6)))) = bboxes[idx][3];
579
580 ++count;
581 }
582 }
583 }
584}
585} // namespace arm_compute