picodet_openvino.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. // reference from https://github.com/RangiLyu/nanodet/tree/main/demo_openvino
  15. #include "picodet_openvino.h"
  16. inline float fast_exp(float x) {
  17. union {
  18. uint32_t i;
  19. float f;
  20. } v{};
  21. v.i = (1 << 23) * (1.4426950409 * x + 126.93490512f);
  22. return v.f;
  23. }
  24. inline float sigmoid(float x) { return 1.0f / (1.0f + fast_exp(-x)); }
  25. template <typename _Tp>
  26. int activation_function_softmax(const _Tp *src, _Tp *dst, int length) {
  27. const _Tp alpha = *std::max_element(src, src + length);
  28. _Tp denominator{0};
  29. for (int i = 0; i < length; ++i) {
  30. dst[i] = fast_exp(src[i] - alpha);
  31. denominator += dst[i];
  32. }
  33. for (int i = 0; i < length; ++i) {
  34. dst[i] /= denominator;
  35. }
  36. return 0;
  37. }
  38. PicoDet::PicoDet(const char *model_path) {
  39. InferenceEngine::Core ie;
  40. InferenceEngine::CNNNetwork model = ie.ReadNetwork(model_path);
  41. // prepare input settings
  42. InferenceEngine::InputsDataMap inputs_map(model.getInputsInfo());
  43. input_name_ = inputs_map.begin()->first;
  44. InferenceEngine::InputInfo::Ptr input_info = inputs_map.begin()->second;
  45. // prepare output settings
  46. InferenceEngine::OutputsDataMap outputs_map(model.getOutputsInfo());
  47. for (auto &output_info : outputs_map) {
  48. output_info.second->setPrecision(InferenceEngine::Precision::FP32);
  49. }
  50. // get network
  51. network_ = ie.LoadNetwork(model, "CPU");
  52. infer_request_ = network_.CreateInferRequest();
  53. }
  54. PicoDet::~PicoDet() {}
  55. void PicoDet::preprocess(cv::Mat &image, InferenceEngine::Blob::Ptr &blob) {
  56. int img_w = image.cols;
  57. int img_h = image.rows;
  58. int channels = 3;
  59. InferenceEngine::MemoryBlob::Ptr mblob =
  60. InferenceEngine::as<InferenceEngine::MemoryBlob>(blob);
  61. if (!mblob) {
  62. THROW_IE_EXCEPTION
  63. << "We expect blob to be inherited from MemoryBlob in matU8ToBlob, "
  64. << "but by fact we were not able to cast inputBlob to MemoryBlob";
  65. }
  66. auto mblobHolder = mblob->wmap();
  67. float *blob_data = mblobHolder.as<float *>();
  68. for (size_t c = 0; c < channels; c++) {
  69. for (size_t h = 0; h < img_h; h++) {
  70. for (size_t w = 0; w < img_w; w++) {
  71. blob_data[c * img_w * img_h + h * img_w + w] =
  72. (float)image.at<cv::Vec3b>(h, w)[c];
  73. }
  74. }
  75. }
  76. }
  77. std::vector<BoxInfo> PicoDet::detect(cv::Mat image, float score_threshold,
  78. float nms_threshold) {
  79. InferenceEngine::Blob::Ptr input_blob = infer_request_.GetBlob(input_name_);
  80. preprocess(image, input_blob);
  81. // do inference
  82. infer_request_.Infer();
  83. // get output
  84. std::vector<std::vector<BoxInfo>> results;
  85. results.resize(this->num_class_);
  86. for (const auto &head_info : this->heads_info_) {
  87. const InferenceEngine::Blob::Ptr dis_pred_blob =
  88. infer_request_.GetBlob(head_info.dis_layer);
  89. const InferenceEngine::Blob::Ptr cls_pred_blob =
  90. infer_request_.GetBlob(head_info.cls_layer);
  91. auto mdis_pred =
  92. InferenceEngine::as<InferenceEngine::MemoryBlob>(dis_pred_blob);
  93. auto mdis_pred_holder = mdis_pred->rmap();
  94. const float *dis_pred = mdis_pred_holder.as<const float *>();
  95. auto mcls_pred =
  96. InferenceEngine::as<InferenceEngine::MemoryBlob>(cls_pred_blob);
  97. auto mcls_pred_holder = mcls_pred->rmap();
  98. const float *cls_pred = mcls_pred_holder.as<const float *>();
  99. this->decode_infer(cls_pred, dis_pred, head_info.stride, score_threshold,
  100. results);
  101. }
  102. std::vector<BoxInfo> dets;
  103. for (int i = 0; i < (int)results.size(); i++) {
  104. this->nms(results[i], nms_threshold);
  105. for (auto &box : results[i]) {
  106. dets.push_back(box);
  107. }
  108. }
  109. return dets;
  110. }
  111. void PicoDet::decode_infer(const float *&cls_pred, const float *&dis_pred,
  112. int stride, float threshold,
  113. std::vector<std::vector<BoxInfo>> &results) {
  114. int feature_h = ceil((float)input_size_ / stride);
  115. int feature_w = ceil((float)input_size_ / stride);
  116. for (int idx = 0; idx < feature_h * feature_w; idx++) {
  117. int row = idx / feature_w;
  118. int col = idx % feature_w;
  119. float score = 0;
  120. int cur_label = 0;
  121. for (int label = 0; label < num_class_; label++) {
  122. if (cls_pred[idx * num_class_ + label] > score) {
  123. score = cls_pred[idx * num_class_ + label];
  124. cur_label = label;
  125. }
  126. }
  127. if (score > threshold) {
  128. const float *bbox_pred = dis_pred + idx * (reg_max_ + 1) * 4;
  129. results[cur_label].push_back(
  130. this->disPred2Bbox(bbox_pred, cur_label, score, col, row, stride));
  131. }
  132. }
  133. }
  134. BoxInfo PicoDet::disPred2Bbox(const float *&dfl_det, int label, float score,
  135. int x, int y, int stride) {
  136. float ct_x = (x + 0.5) * stride;
  137. float ct_y = (y + 0.5) * stride;
  138. std::vector<float> dis_pred;
  139. dis_pred.resize(4);
  140. for (int i = 0; i < 4; i++) {
  141. float dis = 0;
  142. float *dis_after_sm = new float[reg_max_ + 1];
  143. activation_function_softmax(dfl_det + i * (reg_max_ + 1), dis_after_sm,
  144. reg_max_ + 1);
  145. for (int j = 0; j < reg_max_ + 1; j++) {
  146. dis += j * dis_after_sm[j];
  147. }
  148. dis *= stride;
  149. dis_pred[i] = dis;
  150. delete[] dis_after_sm;
  151. }
  152. float xmin = (std::max)(ct_x - dis_pred[0], .0f);
  153. float ymin = (std::max)(ct_y - dis_pred[1], .0f);
  154. float xmax = (std::min)(ct_x + dis_pred[2], (float)this->input_size_);
  155. float ymax = (std::min)(ct_y + dis_pred[3], (float)this->input_size_);
  156. return BoxInfo{xmin, ymin, xmax, ymax, score, label};
  157. }
  158. void PicoDet::nms(std::vector<BoxInfo> &input_boxes, float NMS_THRESH) {
  159. std::sort(input_boxes.begin(), input_boxes.end(),
  160. [](BoxInfo a, BoxInfo b) { return a.score > b.score; });
  161. std::vector<float> vArea(input_boxes.size());
  162. for (int i = 0; i < int(input_boxes.size()); ++i) {
  163. vArea[i] = (input_boxes.at(i).x2 - input_boxes.at(i).x1 + 1) *
  164. (input_boxes.at(i).y2 - input_boxes.at(i).y1 + 1);
  165. }
  166. for (int i = 0; i < int(input_boxes.size()); ++i) {
  167. for (int j = i + 1; j < int(input_boxes.size());) {
  168. float xx1 = (std::max)(input_boxes[i].x1, input_boxes[j].x1);
  169. float yy1 = (std::max)(input_boxes[i].y1, input_boxes[j].y1);
  170. float xx2 = (std::min)(input_boxes[i].x2, input_boxes[j].x2);
  171. float yy2 = (std::min)(input_boxes[i].y2, input_boxes[j].y2);
  172. float w = (std::max)(float(0), xx2 - xx1 + 1);
  173. float h = (std::max)(float(0), yy2 - yy1 + 1);
  174. float inter = w * h;
  175. float ovr = inter / (vArea[i] + vArea[j] - inter);
  176. if (ovr >= NMS_THRESH) {
  177. input_boxes.erase(input_boxes.begin() + j);
  178. vArea.erase(vArea.begin() + j);
  179. } else {
  180. j++;
  181. }
  182. }
  183. }
  184. }