utils.cc 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. //NOLINT
  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 "ultra_infer/vision/detection/contrib/rknpu2/utils.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace detection {
  18. float Clamp(float val, int min, int max) {
  19. return val > min ? (val < max ? val : max) : min;
  20. }
  21. static float CalculateOverlap(float xmin0, float ymin0, float xmax0,
  22. float ymax0, float xmin1, float ymin1,
  23. float xmax1, float ymax1) {
  24. float w = fmax(0.f, fmin(xmax0, xmax1) - fmax(xmin0, xmin1) + 1.0);
  25. float h = fmax(0.f, fmin(ymax0, ymax1) - fmax(ymin0, ymin1) + 1.0);
  26. float i = w * h;
  27. float u = (xmax0 - xmin0 + 1.0) * (ymax0 - ymin0 + 1.0) +
  28. (xmax1 - xmin1 + 1.0) * (ymax1 - ymin1 + 1.0) - i;
  29. return u <= 0.f ? 0.f : (i / u);
  30. }
  31. int NMS(int valid_count, std::vector<float> &output_locations,
  32. std::vector<int> &class_id, std::vector<int> &order, float threshold,
  33. bool class_agnostic) {
  34. for (int i = 0; i < valid_count; ++i) {
  35. if (order[i] == -1) {
  36. continue;
  37. }
  38. int n = order[i];
  39. for (int j = i + 1; j < valid_count; ++j) {
  40. int m = order[j];
  41. if (m == -1) {
  42. continue;
  43. }
  44. if (!class_agnostic && class_id[n] != class_id[m]) {
  45. continue;
  46. }
  47. float xmin0 = output_locations[n * 4 + 0];
  48. float ymin0 = output_locations[n * 4 + 1];
  49. float xmax0 = output_locations[n * 4 + 0] + output_locations[n * 4 + 2];
  50. float ymax0 = output_locations[n * 4 + 1] + output_locations[n * 4 + 3];
  51. float xmin1 = output_locations[m * 4 + 0];
  52. float ymin1 = output_locations[m * 4 + 1];
  53. float xmax1 = output_locations[m * 4 + 0] + output_locations[m * 4 + 2];
  54. float ymax1 = output_locations[m * 4 + 1] + output_locations[m * 4 + 3];
  55. float iou = CalculateOverlap(xmin0, ymin0, xmax0, ymax0, xmin1, ymin1,
  56. xmax1, ymax1);
  57. if (iou > threshold) {
  58. order[j] = -1;
  59. }
  60. }
  61. }
  62. return 0;
  63. }
  64. } // namespace detection
  65. } // namespace vision
  66. } // namespace ultra_infer