utils.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) 2021 PaddlePaddle 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. #include "include/utils.h"
  15. namespace PaddleDetection {
  16. void nms(std::vector<ObjectResult> &input_boxes, float nms_threshold) {
  17. std::sort(input_boxes.begin(),
  18. input_boxes.end(),
  19. [](ObjectResult a, ObjectResult b) { return a.confidence > b.confidence; });
  20. std::vector<float> vArea(input_boxes.size());
  21. for (int i = 0; i < int(input_boxes.size()); ++i) {
  22. vArea[i] = (input_boxes.at(i).rect[2] - input_boxes.at(i).rect[0] + 1)
  23. * (input_boxes.at(i).rect[3] - input_boxes.at(i).rect[1] + 1);
  24. }
  25. for (int i = 0; i < int(input_boxes.size()); ++i) {
  26. for (int j = i + 1; j < int(input_boxes.size());) {
  27. float xx1 = (std::max)(input_boxes[i].rect[0], input_boxes[j].rect[0]);
  28. float yy1 = (std::max)(input_boxes[i].rect[1], input_boxes[j].rect[1]);
  29. float xx2 = (std::min)(input_boxes[i].rect[2], input_boxes[j].rect[2]);
  30. float yy2 = (std::min)(input_boxes[i].rect[3], input_boxes[j].rect[3]);
  31. float w = (std::max)(float(0), xx2 - xx1 + 1);
  32. float h = (std::max)(float(0), yy2 - yy1 + 1);
  33. float inter = w * h;
  34. float ovr = inter / (vArea[i] + vArea[j] - inter);
  35. if (ovr >= nms_threshold) {
  36. input_boxes.erase(input_boxes.begin() + j);
  37. vArea.erase(vArea.begin() + j);
  38. }
  39. else {
  40. j++;
  41. }
  42. }
  43. }
  44. }
  45. } // namespace PaddleDetection