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

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