plugin  0.1.0
nms.hpp
1 /*
2 // Copyright (C) 2021-2024 Intel Corporation
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 #pragma once
18 
19 #include "opencv2/core.hpp"
20 #include <numeric>
21 #include <vector>
22 
23 struct Anchor {
24  float left;
25  float top;
26  float right;
27  float bottom;
28 
29  float getWidth() const {
30  return (right - left) + 1.0f;
31  }
32  float getHeight() const {
33  return (bottom - top) + 1.0f;
34  }
35  float getXCenter() const {
36  return left + (getWidth() - 1.0f) / 2.0f;
37  }
38  float getYCenter() const {
39  return top + (getHeight() - 1.0f) / 2.0f;
40  }
41 };
42 
43 template <typename Anchor>
44 std::vector<int> nms(const std::vector<Anchor>& boxes, const std::vector<float>& scores,
45  const float thresh, bool includeBoundaries=false) {
46  std::vector<float> areas(boxes.size());
47  for (size_t i = 0; i < boxes.size(); ++i) {
48  areas[i] = (boxes[i].right - boxes[i].left + includeBoundaries) * (boxes[i].bottom - boxes[i].top + includeBoundaries);
49  }
50  std::vector<int> order(scores.size());
51  std::iota(order.begin(), order.end(), 0);
52  std::sort(order.begin(), order.end(), [&scores](int o1, int o2) { return scores[o1] > scores[o2]; });
53 
54  size_t ordersNum = 0;
55  for (; ordersNum < order.size() && scores[order[ordersNum]] >= 0; ordersNum++);
56 
57  std::vector<int> keep;
58  bool shouldContinue = true;
59  for (size_t i = 0; shouldContinue && i < ordersNum; ++i) {
60  auto idx1 = order[i];
61  if (idx1 >= 0) {
62  keep.push_back(idx1);
63  shouldContinue = false;
64  for (size_t j = i + 1; j < ordersNum; ++j) {
65  auto idx2 = order[j];
66  if (idx2 >= 0) {
67  shouldContinue = true;
68  auto overlappingWidth = std::fminf(boxes[idx1].right, boxes[idx2].right) - std::fmaxf(boxes[idx1].left, boxes[idx2].left);
69  auto overlappingHeight = std::fminf(boxes[idx1].bottom, boxes[idx2].bottom) - std::fmaxf(boxes[idx1].top, boxes[idx2].top);
70  auto intersection = overlappingWidth > 0 && overlappingHeight > 0 ? overlappingWidth * overlappingHeight : 0;
71  auto overlap = intersection / (areas[idx1] + areas[idx2] - intersection);
72 
73  if (overlap >= thresh) {
74  order[j] = -1;
75  }
76  }
77  }
78  }
79  }
80  return keep;
81 }
Definition: nms.hpp:23