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.

yolox.cpp 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Copyright 2020 Tencent
  2. // Copyright 2020-2021 Megvii Inc.
  3. // SPDX-License-Identifier: BSD-3-Clause
  4. #include "layer.h"
  5. #include "net.h"
  6. #if defined(USE_NCNN_SIMPLEOCV)
  7. #include "simpleocv.h"
  8. #else
  9. #include <opencv2/core/core.hpp>
  10. #include <opencv2/highgui/highgui.hpp>
  11. #include <opencv2/imgproc/imgproc.hpp>
  12. #endif
  13. #include <float.h>
  14. #include <stdio.h>
  15. #include <vector>
  16. #define YOLOX_NMS_THRESH 0.45 // nms threshold
  17. #define YOLOX_CONF_THRESH 0.25 // threshold of bounding box prob
  18. #define YOLOX_TARGET_SIZE 640 // target image size after resize, might use 416 for small model
  19. // YOLOX use the same focus in yolov5
  20. class YoloV5Focus : public ncnn::Layer
  21. {
  22. public:
  23. YoloV5Focus()
  24. {
  25. one_blob_only = true;
  26. }
  27. virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
  28. {
  29. int w = bottom_blob.w;
  30. int h = bottom_blob.h;
  31. int channels = bottom_blob.c;
  32. int outw = w / 2;
  33. int outh = h / 2;
  34. int outc = channels * 4;
  35. top_blob.create(outw, outh, outc, 4u, 1, opt.blob_allocator);
  36. if (top_blob.empty())
  37. return -100;
  38. #pragma omp parallel for num_threads(opt.num_threads)
  39. for (int p = 0; p < outc; p++)
  40. {
  41. const float* ptr = bottom_blob.channel(p % channels).row((p / channels) % 2) + ((p / channels) / 2);
  42. float* outptr = top_blob.channel(p);
  43. for (int i = 0; i < outh; i++)
  44. {
  45. for (int j = 0; j < outw; j++)
  46. {
  47. *outptr = *ptr;
  48. outptr += 1;
  49. ptr += 2;
  50. }
  51. ptr += w;
  52. }
  53. }
  54. return 0;
  55. }
  56. };
  57. DEFINE_LAYER_CREATOR(YoloV5Focus)
  58. struct Object
  59. {
  60. cv::Rect_<float> rect;
  61. int label;
  62. float prob;
  63. };
  64. struct GridAndStride
  65. {
  66. int grid0;
  67. int grid1;
  68. int stride;
  69. };
  70. static inline float intersection_area(const Object& a, const Object& b)
  71. {
  72. cv::Rect_<float> inter = a.rect & b.rect;
  73. return inter.area();
  74. }
  75. static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
  76. {
  77. int i = left;
  78. int j = right;
  79. float p = faceobjects[(left + right) / 2].prob;
  80. while (i <= j)
  81. {
  82. while (faceobjects[i].prob > p)
  83. i++;
  84. while (faceobjects[j].prob < p)
  85. j--;
  86. if (i <= j)
  87. {
  88. // swap
  89. std::swap(faceobjects[i], faceobjects[j]);
  90. i++;
  91. j--;
  92. }
  93. }
  94. #pragma omp parallel sections
  95. {
  96. #pragma omp section
  97. {
  98. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  99. }
  100. #pragma omp section
  101. {
  102. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  103. }
  104. }
  105. }
  106. static void qsort_descent_inplace(std::vector<Object>& objects)
  107. {
  108. if (objects.empty())
  109. return;
  110. qsort_descent_inplace(objects, 0, objects.size() - 1);
  111. }
  112. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  113. {
  114. picked.clear();
  115. const int n = faceobjects.size();
  116. std::vector<float> areas(n);
  117. for (int i = 0; i < n; i++)
  118. {
  119. areas[i] = faceobjects[i].rect.area();
  120. }
  121. for (int i = 0; i < n; i++)
  122. {
  123. const Object& a = faceobjects[i];
  124. int keep = 1;
  125. for (int j = 0; j < (int)picked.size(); j++)
  126. {
  127. const Object& b = faceobjects[picked[j]];
  128. if (!agnostic && a.label != b.label)
  129. continue;
  130. // intersection over union
  131. float inter_area = intersection_area(a, b);
  132. float union_area = areas[i] + areas[picked[j]] - inter_area;
  133. // float IoU = inter_area / union_area
  134. if (inter_area / union_area > nms_threshold)
  135. keep = 0;
  136. }
  137. if (keep)
  138. picked.push_back(i);
  139. }
  140. }
  141. static void generate_grids_and_stride(const int target_w, const int target_h, std::vector<int>& strides, std::vector<GridAndStride>& grid_strides)
  142. {
  143. for (int i = 0; i < (int)strides.size(); i++)
  144. {
  145. int stride = strides[i];
  146. int num_grid_w = target_w / stride;
  147. int num_grid_h = target_h / stride;
  148. for (int g1 = 0; g1 < num_grid_h; g1++)
  149. {
  150. for (int g0 = 0; g0 < num_grid_w; g0++)
  151. {
  152. GridAndStride gs;
  153. gs.grid0 = g0;
  154. gs.grid1 = g1;
  155. gs.stride = stride;
  156. grid_strides.push_back(gs);
  157. }
  158. }
  159. }
  160. }
  161. static void generate_yolox_proposals(std::vector<GridAndStride> grid_strides, const ncnn::Mat& feat_blob, float prob_threshold, std::vector<Object>& objects)
  162. {
  163. const int num_grid = feat_blob.h;
  164. const int num_class = feat_blob.w - 5;
  165. const int num_anchors = grid_strides.size();
  166. const float* feat_ptr = feat_blob.channel(0);
  167. for (int anchor_idx = 0; anchor_idx < num_anchors; anchor_idx++)
  168. {
  169. const int grid0 = grid_strides[anchor_idx].grid0;
  170. const int grid1 = grid_strides[anchor_idx].grid1;
  171. const int stride = grid_strides[anchor_idx].stride;
  172. // yolox/models/yolo_head.py decode logic
  173. // outputs[..., :2] = (outputs[..., :2] + grids) * strides
  174. // outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides
  175. float x_center = (feat_ptr[0] + grid0) * stride;
  176. float y_center = (feat_ptr[1] + grid1) * stride;
  177. float w = exp(feat_ptr[2]) * stride;
  178. float h = exp(feat_ptr[3]) * stride;
  179. float x0 = x_center - w * 0.5f;
  180. float y0 = y_center - h * 0.5f;
  181. float box_objectness = feat_ptr[4];
  182. for (int class_idx = 0; class_idx < num_class; class_idx++)
  183. {
  184. float box_cls_score = feat_ptr[5 + class_idx];
  185. float box_prob = box_objectness * box_cls_score;
  186. if (box_prob > prob_threshold)
  187. {
  188. Object obj;
  189. obj.rect.x = x0;
  190. obj.rect.y = y0;
  191. obj.rect.width = w;
  192. obj.rect.height = h;
  193. obj.label = class_idx;
  194. obj.prob = box_prob;
  195. objects.push_back(obj);
  196. }
  197. } // class loop
  198. feat_ptr += feat_blob.w;
  199. } // point anchor loop
  200. }
  201. static int detect_yolox(const cv::Mat& bgr, std::vector<Object>& objects)
  202. {
  203. ncnn::Net yolox;
  204. yolox.opt.use_vulkan_compute = true;
  205. // yolox.opt.use_bf16_storage = true;
  206. // Focus in yolov5
  207. yolox.register_custom_layer("YoloV5Focus", YoloV5Focus_layer_creator);
  208. // original pretrained model from https://github.com/Megvii-BaseDetection/YOLOX
  209. // ncnn model param: https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s_ncnn.tar.gz
  210. // NOTE that newest version YOLOX remove normalization of model (minus mean and then div by std),
  211. // which might cause your model outputs becoming a total mess, plz check carefully.
  212. if (yolox.load_param("yolox.param"))
  213. exit(-1);
  214. if (yolox.load_model("yolox.bin"))
  215. exit(-1);
  216. int img_w = bgr.cols;
  217. int img_h = bgr.rows;
  218. int w = img_w;
  219. int h = img_h;
  220. float scale = 1.f;
  221. if (w > h)
  222. {
  223. scale = (float)YOLOX_TARGET_SIZE / w;
  224. w = YOLOX_TARGET_SIZE;
  225. h = h * scale;
  226. }
  227. else
  228. {
  229. scale = (float)YOLOX_TARGET_SIZE / h;
  230. h = YOLOX_TARGET_SIZE;
  231. w = w * scale;
  232. }
  233. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, img_w, img_h, w, h);
  234. // pad to YOLOX_TARGET_SIZE rectangle
  235. int wpad = (w + 31) / 32 * 32 - w;
  236. int hpad = (h + 31) / 32 * 32 - h;
  237. ncnn::Mat in_pad;
  238. // different from yolov5, yolox only pad on bottom and right side,
  239. // which means users don't need to extra padding info to decode boxes coordinate.
  240. ncnn::copy_make_border(in, in_pad, 0, hpad, 0, wpad, ncnn::BORDER_CONSTANT, 114.f);
  241. ncnn::Extractor ex = yolox.create_extractor();
  242. ex.input("images", in_pad);
  243. std::vector<Object> proposals;
  244. {
  245. ncnn::Mat out;
  246. ex.extract("output", out);
  247. static const int stride_arr[] = {8, 16, 32}; // might have stride=64 in YOLOX
  248. std::vector<int> strides(stride_arr, stride_arr + sizeof(stride_arr) / sizeof(stride_arr[0]));
  249. std::vector<GridAndStride> grid_strides;
  250. generate_grids_and_stride(in_pad.w, in_pad.h, strides, grid_strides);
  251. generate_yolox_proposals(grid_strides, out, YOLOX_CONF_THRESH, proposals);
  252. }
  253. // sort all proposals by score from highest to lowest
  254. qsort_descent_inplace(proposals);
  255. // apply nms with nms_threshold
  256. std::vector<int> picked;
  257. nms_sorted_bboxes(proposals, picked, YOLOX_NMS_THRESH);
  258. int count = picked.size();
  259. objects.resize(count);
  260. for (int i = 0; i < count; i++)
  261. {
  262. objects[i] = proposals[picked[i]];
  263. // adjust offset to original unpadded
  264. float x0 = (objects[i].rect.x) / scale;
  265. float y0 = (objects[i].rect.y) / scale;
  266. float x1 = (objects[i].rect.x + objects[i].rect.width) / scale;
  267. float y1 = (objects[i].rect.y + objects[i].rect.height) / scale;
  268. // clip
  269. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  270. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  271. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  272. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  273. objects[i].rect.x = x0;
  274. objects[i].rect.y = y0;
  275. objects[i].rect.width = x1 - x0;
  276. objects[i].rect.height = y1 - y0;
  277. }
  278. return 0;
  279. }
  280. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  281. {
  282. static const char* class_names[] = {
  283. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  284. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  285. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  286. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  287. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  288. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  289. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  290. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  291. "hair drier", "toothbrush"
  292. };
  293. cv::Mat image = bgr.clone();
  294. for (size_t i = 0; i < objects.size(); i++)
  295. {
  296. const Object& obj = objects[i];
  297. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  298. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  299. cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
  300. char text[256];
  301. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  302. int baseLine = 0;
  303. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  304. int x = obj.rect.x;
  305. int y = obj.rect.y - label_size.height - baseLine;
  306. if (y < 0)
  307. y = 0;
  308. if (x + label_size.width > image.cols)
  309. x = image.cols - label_size.width;
  310. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  311. cv::Scalar(255, 255, 255), -1);
  312. cv::putText(image, text, cv::Point(x, y + label_size.height),
  313. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  314. }
  315. cv::imshow("image", image);
  316. cv::waitKey(0);
  317. }
  318. int main(int argc, char** argv)
  319. {
  320. if (argc != 2)
  321. {
  322. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  323. return -1;
  324. }
  325. const char* imagepath = argv[1];
  326. cv::Mat m = cv::imread(imagepath, 1);
  327. if (m.empty())
  328. {
  329. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  330. return -1;
  331. }
  332. std::vector<Object> objects;
  333. detect_yolox(m, objects);
  334. draw_objects(m, objects);
  335. return 0;
  336. }