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 10 kB

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