You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

detect_yolox.cpp 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /**
  2. * \file example/cpp_example/cv/detect_yolox.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include <thread>
  12. #include "example.h"
  13. #if LITE_BUILD_WITH_MGE
  14. #include <cstdio>
  15. #include "misc.h"
  16. #define STB_IMAGE_STATIC
  17. #define STB_IMAGE_IMPLEMENTATION
  18. #include "stb_image.h"
  19. #define STB_IMAGE_RESIZE_STATIC
  20. #define STB_IMAGE_RESIZE_IMPLEMENTATION
  21. #include "stb_image_resize.h"
  22. #define STB_IMAGE_WRITE_STATIC
  23. #define STB_IMAGE_WRITE_IMPLEMENTATION
  24. #include "stb_image_write.h"
  25. #define NMS_THRESH 0.25
  26. #define BBOX_CONF_THRESH 0.6
  27. constexpr int INPUT_W = 640;
  28. constexpr int INPUT_H = 640;
  29. using namespace lite;
  30. using namespace example;
  31. namespace {
  32. void preprocess_image(
  33. uint8_t* image, const int width, const int height, const int channel,
  34. std::shared_ptr<Tensor> tensor) {
  35. auto layout = tensor->get_layout();
  36. for (size_t i = 0; i < layout.ndim; i++) {
  37. printf("model input shape[%zu]=%zu \n", i, layout.shapes[i]);
  38. }
  39. //! resize to target shape
  40. float r = std::min(INPUT_W / (width * 1.0), INPUT_H / (height * 1.0));
  41. int unpad_w = r * width;
  42. int unpad_h = r * height;
  43. std::shared_ptr<std::vector<uint8_t>> resize_int8 =
  44. std::make_shared<std::vector<uint8_t>>(unpad_w * unpad_h * channel);
  45. stbir_resize_uint8(
  46. image, width, height, 0, resize_int8->data(), unpad_w, unpad_h, 0, channel);
  47. std::shared_ptr<std::vector<uint8_t>> padded;
  48. if (unpad_h != INPUT_H || unpad_w != INPUT_W) {
  49. padded = std::make_shared<std::vector<uint8_t>>(
  50. INPUT_H * INPUT_W * channel, 114);
  51. for (int h = 0; h < unpad_h; h++) {
  52. for (int w = 0; w < unpad_w; w++) {
  53. for (int c = 0; c < channel; c++) {
  54. (*padded)[h * INPUT_W * channel + w * channel + c] =
  55. (*resize_int8)[h * unpad_w * channel + w * channel + c];
  56. }
  57. }
  58. }
  59. } else {
  60. padded = resize_int8;
  61. }
  62. tensor->set_layout({{1, 3, 640, 640}, 4});
  63. std::vector<float> mean = {0.485, 0.456, 0.406};
  64. std::vector<float> std = {0.229, 0.224, 0.225};
  65. //! convert form rgb to bgr, relayout from hwc to chw, normalization copy to tensor
  66. float* in_data = static_cast<float*>(tensor->get_memory_ptr());
  67. size_t pixels = INPUT_H * INPUT_W;
  68. for (size_t i = 0; i < pixels; i++) {
  69. in_data[i] = (padded->at(i * channel + 0) / 255.0f - mean[0]) / std[0];
  70. in_data[i + 1 * pixels] =
  71. (padded->at(i * channel + 1) / 255.0f - mean[1]) / std[1];
  72. in_data[i + 2 * pixels] =
  73. (padded->at(i * channel + 2) / 255.0f - mean[2]) / std[2];
  74. }
  75. }
  76. struct Rect {
  77. float x;
  78. float y;
  79. float height;
  80. float width;
  81. float area() const { return height * width; }
  82. Rect operator&(Rect other) const {
  83. Rect ret;
  84. float x_start = std::max(x, other.x);
  85. float x_end = std::min(x + width, other.width);
  86. ret.x = x_start;
  87. ret.width = (x_end - x_start) > 0 ? x_end - x_start : 0;
  88. float y_start = std::max(y, other.y);
  89. float y_end = std::min(y + height, other.height);
  90. ret.y = y_start;
  91. ret.height = (y_end - y_start) > 0 ? y_end - y_start : 0;
  92. return ret;
  93. }
  94. };
  95. struct Object {
  96. Rect rect;
  97. int label;
  98. float prob;
  99. };
  100. struct GridAndStride {
  101. int grid0;
  102. int grid1;
  103. int stride;
  104. };
  105. static void generate_grids_and_stride(
  106. const int target_size, std::vector<int>& strides,
  107. std::vector<GridAndStride>& grid_strides) {
  108. for (auto stride : strides) {
  109. int num_grid = target_size / stride;
  110. for (int g1 = 0; g1 < num_grid; g1++) {
  111. for (int g0 = 0; g0 < num_grid; g0++) {
  112. grid_strides.push_back((GridAndStride){g0, g1, stride});
  113. }
  114. }
  115. }
  116. }
  117. static void generate_yolox_proposals(
  118. std::vector<GridAndStride> grid_strides, const float* feat_ptr,
  119. float prob_threshold, std::vector<Object>& objects) {
  120. const int num_class = 80;
  121. const int num_anchors = grid_strides.size();
  122. for (int anchor_idx = 0; anchor_idx < num_anchors; anchor_idx++) {
  123. const int grid0 = grid_strides[anchor_idx].grid0;
  124. const int grid1 = grid_strides[anchor_idx].grid1;
  125. const int stride = grid_strides[anchor_idx].stride;
  126. const int basic_pos = anchor_idx * 85;
  127. float x_center = (feat_ptr[basic_pos + 0] + grid0) * stride;
  128. float y_center = (feat_ptr[basic_pos + 1] + grid1) * stride;
  129. float w = exp(feat_ptr[basic_pos + 2]) * stride;
  130. float h = exp(feat_ptr[basic_pos + 3]) * stride;
  131. float x0 = x_center - w * 0.5f;
  132. float y0 = y_center - h * 0.5f;
  133. float box_objectness = feat_ptr[basic_pos + 4];
  134. for (int class_idx = 0; class_idx < num_class; class_idx++) {
  135. float box_cls_score = feat_ptr[basic_pos + 5 + class_idx];
  136. float box_prob = box_objectness * box_cls_score;
  137. if (box_prob > prob_threshold) {
  138. Object obj;
  139. obj.rect.x = x0;
  140. obj.rect.y = y0;
  141. obj.rect.width = w;
  142. obj.rect.height = h;
  143. obj.label = class_idx;
  144. obj.prob = box_prob;
  145. objects.push_back(obj);
  146. }
  147. } // class loop
  148. } // point anchor loop
  149. }
  150. void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right) {
  151. int i = left;
  152. int j = right;
  153. float p = faceobjects[(left + right) / 2].prob;
  154. while (i <= j) {
  155. while (faceobjects[i].prob > p)
  156. i++;
  157. while (faceobjects[j].prob < p)
  158. j--;
  159. if (i <= j) {
  160. // swap
  161. std::swap(faceobjects[i], faceobjects[j]);
  162. i++;
  163. j--;
  164. }
  165. }
  166. if (left < j)
  167. qsort_descent_inplace(faceobjects, left, j);
  168. if (i < right)
  169. qsort_descent_inplace(faceobjects, i, right);
  170. }
  171. void qsort_descent_inplace(std::vector<Object>& objects) {
  172. if (objects.empty())
  173. return;
  174. qsort_descent_inplace(objects, 0, objects.size() - 1);
  175. }
  176. inline float intersection_area(const Object& a, const Object& b) {
  177. Rect inter = a.rect & b.rect;
  178. return inter.area();
  179. }
  180. void nms_sorted_bboxes(
  181. const std::vector<Object>& faceobjects, std::vector<int>& picked,
  182. float nms_threshold) {
  183. picked.clear();
  184. const int n = faceobjects.size();
  185. std::vector<float> areas(n);
  186. for (int i = 0; i < n; i++) {
  187. areas[i] = faceobjects[i].rect.area();
  188. }
  189. for (int i = 0; i < n; i++) {
  190. const Object& a = faceobjects[i];
  191. int keep = 1;
  192. for (int j = 0; j < (int)picked.size(); j++) {
  193. const Object& b = faceobjects[picked[j]];
  194. // intersection over union
  195. float inter_area = intersection_area(a, b);
  196. float union_area = areas[i] + areas[picked[j]] - inter_area;
  197. // float IoU = inter_area / union_area
  198. if (inter_area / union_area > nms_threshold)
  199. keep = 0;
  200. }
  201. if (keep)
  202. picked.push_back(i);
  203. }
  204. }
  205. void decode_outputs(
  206. const float* prob, std::vector<Object>& objects, float scale, const int img_w,
  207. const int img_h) {
  208. std::vector<Object> proposals;
  209. std::vector<int> strides = {8, 16, 32};
  210. std::vector<GridAndStride> grid_strides;
  211. generate_grids_and_stride(INPUT_W, strides, grid_strides);
  212. generate_yolox_proposals(grid_strides, prob, BBOX_CONF_THRESH, proposals);
  213. qsort_descent_inplace(proposals);
  214. std::vector<int> picked;
  215. nms_sorted_bboxes(proposals, picked, NMS_THRESH);
  216. int count = picked.size();
  217. objects.resize(count);
  218. for (int i = 0; i < count; i++) {
  219. objects[i] = proposals[picked[i]];
  220. // adjust offset to original unpadded
  221. float x0 = (objects[i].rect.x) / scale;
  222. float y0 = (objects[i].rect.y) / scale;
  223. float x1 = (objects[i].rect.x + objects[i].rect.width) / scale;
  224. float y1 = (objects[i].rect.y + objects[i].rect.height) / scale;
  225. // clip
  226. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  227. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  228. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  229. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  230. objects[i].rect.x = x0;
  231. objects[i].rect.y = y0;
  232. objects[i].rect.width = x1 - x0;
  233. objects[i].rect.height = y1 - y0;
  234. }
  235. }
  236. void draw_objects(
  237. uint8_t* image, int width, int height, int channel,
  238. const std::vector<Object>& objects) {
  239. (void)image;
  240. (void)width;
  241. (void)height;
  242. (void)channel;
  243. for (size_t i = 0; i < objects.size(); i++) {
  244. const Object& obj = objects[i];
  245. printf("Object: %d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  246. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  247. }
  248. }
  249. bool detect_yolox(const Args& args) {
  250. std::string network_path = args.model_path;
  251. std::string input_path = args.input_path;
  252. int width, height, channel;
  253. uint8_t* image = stbi_load(input_path.c_str(), &width, &height, &channel, 0);
  254. printf("Input image %s with height=%d, width=%d, channel=%d\n", input_path.c_str(),
  255. width, height, channel);
  256. //! create and load the network
  257. std::shared_ptr<Network> network = std::make_shared<Network>();
  258. network->load_model(network_path);
  259. //! set input data to input tensor
  260. auto input_tensor = network->get_io_tensor("data");
  261. preprocess_image(image, width, height, channel, input_tensor);
  262. network->forward();
  263. network->wait();
  264. float* predict_ptr =
  265. static_cast<float*>(network->get_output_tensor(0)->get_memory_ptr());
  266. float scale = std::min(INPUT_W / (width * 1.0), INPUT_H / (height * 1.0));
  267. std::vector<Object> objects;
  268. decode_outputs(predict_ptr, objects, scale, width, height);
  269. draw_objects(image, width, height, channel, objects);
  270. stbi_image_free(image);
  271. return 0;
  272. }
  273. } // namespace
  274. REGIST_EXAMPLE("detect_yolox", detect_yolox);
  275. #endif
  276. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}