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.

yolov5.cpp 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2020 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include "layer.h"
  4. #include "net.h"
  5. #if defined(USE_NCNN_SIMPLEOCV)
  6. #include "simpleocv.h"
  7. #else
  8. #include <opencv2/core/core.hpp>
  9. #include <opencv2/highgui/highgui.hpp>
  10. #include <opencv2/imgproc/imgproc.hpp>
  11. #endif
  12. #include <float.h>
  13. #include <stdio.h>
  14. #include <vector>
  15. //#define YOLOV5_V60 1 //YOLOv5 v6.0
  16. #define YOLOV5_V62 1 //YOLOv5 v6.2 export onnx model method https://github.com/shaoshengsong/yolov5_62_export_ncnn
  17. #if YOLOV5_V60 || YOLOV5_V62
  18. #define MAX_STRIDE 64
  19. #else
  20. #define MAX_STRIDE 32
  21. class YoloV5Focus : public ncnn::Layer
  22. {
  23. public:
  24. YoloV5Focus()
  25. {
  26. one_blob_only = true;
  27. }
  28. virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
  29. {
  30. int w = bottom_blob.w;
  31. int h = bottom_blob.h;
  32. int channels = bottom_blob.c;
  33. int outw = w / 2;
  34. int outh = h / 2;
  35. int outc = channels * 4;
  36. top_blob.create(outw, outh, outc, 4u, 1, opt.blob_allocator);
  37. if (top_blob.empty())
  38. return -100;
  39. #pragma omp parallel for num_threads(opt.num_threads)
  40. for (int p = 0; p < outc; p++)
  41. {
  42. const float* ptr = bottom_blob.channel(p % channels).row((p / channels) % 2) + ((p / channels) / 2);
  43. float* outptr = top_blob.channel(p);
  44. for (int i = 0; i < outh; i++)
  45. {
  46. for (int j = 0; j < outw; j++)
  47. {
  48. *outptr = *ptr;
  49. outptr += 1;
  50. ptr += 2;
  51. }
  52. ptr += w;
  53. }
  54. }
  55. return 0;
  56. }
  57. };
  58. DEFINE_LAYER_CREATOR(YoloV5Focus)
  59. #endif //YOLOV5_V60 YOLOV5_V62
  60. struct Object
  61. {
  62. cv::Rect_<float> rect;
  63. int label;
  64. float prob;
  65. };
  66. static inline float intersection_area(const Object& a, const Object& b)
  67. {
  68. cv::Rect_<float> inter = a.rect & b.rect;
  69. return inter.area();
  70. }
  71. static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
  72. {
  73. int i = left;
  74. int j = right;
  75. float p = faceobjects[(left + right) / 2].prob;
  76. while (i <= j)
  77. {
  78. while (faceobjects[i].prob > p)
  79. i++;
  80. while (faceobjects[j].prob < p)
  81. j--;
  82. if (i <= j)
  83. {
  84. // swap
  85. std::swap(faceobjects[i], faceobjects[j]);
  86. i++;
  87. j--;
  88. }
  89. }
  90. #pragma omp parallel sections
  91. {
  92. #pragma omp section
  93. {
  94. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  95. }
  96. #pragma omp section
  97. {
  98. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  99. }
  100. }
  101. }
  102. static void qsort_descent_inplace(std::vector<Object>& faceobjects)
  103. {
  104. if (faceobjects.empty())
  105. return;
  106. qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
  107. }
  108. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  109. {
  110. picked.clear();
  111. const int n = faceobjects.size();
  112. std::vector<float> areas(n);
  113. for (int i = 0; i < n; i++)
  114. {
  115. areas[i] = faceobjects[i].rect.area();
  116. }
  117. for (int i = 0; i < n; i++)
  118. {
  119. const Object& a = faceobjects[i];
  120. int keep = 1;
  121. for (int j = 0; j < (int)picked.size(); j++)
  122. {
  123. const Object& b = faceobjects[picked[j]];
  124. if (!agnostic && a.label != b.label)
  125. continue;
  126. // intersection over union
  127. float inter_area = intersection_area(a, b);
  128. float union_area = areas[i] + areas[picked[j]] - inter_area;
  129. // float IoU = inter_area / union_area
  130. if (inter_area / union_area > nms_threshold)
  131. keep = 0;
  132. }
  133. if (keep)
  134. picked.push_back(i);
  135. }
  136. }
  137. static inline float sigmoid(float x)
  138. {
  139. return static_cast<float>(1.f / (1.f + exp(-x)));
  140. }
  141. static void generate_proposals(const ncnn::Mat& anchors, int stride, const ncnn::Mat& in_pad, const ncnn::Mat& feat_blob, float prob_threshold, std::vector<Object>& objects)
  142. {
  143. const int num_grid = feat_blob.h;
  144. int num_grid_x;
  145. int num_grid_y;
  146. if (in_pad.w > in_pad.h)
  147. {
  148. num_grid_x = in_pad.w / stride;
  149. num_grid_y = num_grid / num_grid_x;
  150. }
  151. else
  152. {
  153. num_grid_y = in_pad.h / stride;
  154. num_grid_x = num_grid / num_grid_y;
  155. }
  156. const int num_class = feat_blob.w - 5;
  157. const int num_anchors = anchors.w / 2;
  158. for (int q = 0; q < num_anchors; q++)
  159. {
  160. const float anchor_w = anchors[q * 2];
  161. const float anchor_h = anchors[q * 2 + 1];
  162. const ncnn::Mat feat = feat_blob.channel(q);
  163. for (int i = 0; i < num_grid_y; i++)
  164. {
  165. for (int j = 0; j < num_grid_x; j++)
  166. {
  167. const float* featptr = feat.row(i * num_grid_x + j);
  168. float box_confidence = sigmoid(featptr[4]);
  169. if (box_confidence >= prob_threshold)
  170. {
  171. // find class index with max class score
  172. int class_index = 0;
  173. float class_score = -FLT_MAX;
  174. for (int k = 0; k < num_class; k++)
  175. {
  176. float score = featptr[5 + k];
  177. if (score > class_score)
  178. {
  179. class_index = k;
  180. class_score = score;
  181. }
  182. }
  183. float confidence = box_confidence * sigmoid(class_score);
  184. if (confidence >= prob_threshold)
  185. {
  186. // yolov5/models/yolo.py Detect forward
  187. // y = x[i].sigmoid()
  188. // y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
  189. // y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
  190. float dx = sigmoid(featptr[0]);
  191. float dy = sigmoid(featptr[1]);
  192. float dw = sigmoid(featptr[2]);
  193. float dh = sigmoid(featptr[3]);
  194. float pb_cx = (dx * 2.f - 0.5f + j) * stride;
  195. float pb_cy = (dy * 2.f - 0.5f + i) * stride;
  196. float pb_w = pow(dw * 2.f, 2) * anchor_w;
  197. float pb_h = pow(dh * 2.f, 2) * anchor_h;
  198. float x0 = pb_cx - pb_w * 0.5f;
  199. float y0 = pb_cy - pb_h * 0.5f;
  200. float x1 = pb_cx + pb_w * 0.5f;
  201. float y1 = pb_cy + pb_h * 0.5f;
  202. Object obj;
  203. obj.rect.x = x0;
  204. obj.rect.y = y0;
  205. obj.rect.width = x1 - x0;
  206. obj.rect.height = y1 - y0;
  207. obj.label = class_index;
  208. obj.prob = confidence;
  209. objects.push_back(obj);
  210. }
  211. }
  212. }
  213. }
  214. }
  215. }
  216. static int detect_yolov5(const cv::Mat& bgr, std::vector<Object>& objects)
  217. {
  218. ncnn::Net yolov5;
  219. yolov5.opt.use_vulkan_compute = true;
  220. // yolov5.opt.use_bf16_storage = true;
  221. // original pretrained model from https://github.com/ultralytics/yolov5
  222. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  223. #if YOLOV5_V62
  224. if (yolov5.load_param("yolov5s_6.2.param"))
  225. exit(-1);
  226. if (yolov5.load_model("yolov5s_6.2.bin"))
  227. exit(-1);
  228. #elif YOLOV5_V60
  229. if (yolov5.load_param("yolov5s_6.0.param"))
  230. exit(-1);
  231. if (yolov5.load_model("yolov5s_6.0.bin"))
  232. exit(-1);
  233. #else
  234. yolov5.register_custom_layer("YoloV5Focus", YoloV5Focus_layer_creator);
  235. if (yolov5.load_param("yolov5s.param"))
  236. exit(-1);
  237. if (yolov5.load_model("yolov5s.bin"))
  238. exit(-1);
  239. #endif
  240. const int target_size = 640;
  241. const float prob_threshold = 0.25f;
  242. const float nms_threshold = 0.45f;
  243. int img_w = bgr.cols;
  244. int img_h = bgr.rows;
  245. // letterbox pad to multiple of MAX_STRIDE
  246. int w = img_w;
  247. int h = img_h;
  248. float scale = 1.f;
  249. if (w > h)
  250. {
  251. scale = (float)target_size / w;
  252. w = target_size;
  253. h = h * scale;
  254. }
  255. else
  256. {
  257. scale = (float)target_size / h;
  258. h = target_size;
  259. w = w * scale;
  260. }
  261. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  262. // pad to target_size rectangle
  263. // yolov5/utils/datasets.py letterbox
  264. int wpad = (w + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - w;
  265. int hpad = (h + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - h;
  266. ncnn::Mat in_pad;
  267. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  268. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  269. in_pad.substract_mean_normalize(0, norm_vals);
  270. ncnn::Extractor ex = yolov5.create_extractor();
  271. ex.input("images", in_pad);
  272. std::vector<Object> proposals;
  273. // anchor setting from yolov5/models/yolov5s.yaml
  274. // stride 8
  275. {
  276. ncnn::Mat out;
  277. ex.extract("output", out);
  278. ncnn::Mat anchors(6);
  279. anchors[0] = 10.f;
  280. anchors[1] = 13.f;
  281. anchors[2] = 16.f;
  282. anchors[3] = 30.f;
  283. anchors[4] = 33.f;
  284. anchors[5] = 23.f;
  285. std::vector<Object> objects8;
  286. generate_proposals(anchors, 8, in_pad, out, prob_threshold, objects8);
  287. proposals.insert(proposals.end(), objects8.begin(), objects8.end());
  288. }
  289. // stride 16
  290. {
  291. ncnn::Mat out;
  292. #if YOLOV5_V62
  293. ex.extract("353", out);
  294. #elif YOLOV5_V60
  295. ex.extract("376", out);
  296. #else
  297. ex.extract("781", out);
  298. #endif
  299. ncnn::Mat anchors(6);
  300. anchors[0] = 30.f;
  301. anchors[1] = 61.f;
  302. anchors[2] = 62.f;
  303. anchors[3] = 45.f;
  304. anchors[4] = 59.f;
  305. anchors[5] = 119.f;
  306. std::vector<Object> objects16;
  307. generate_proposals(anchors, 16, in_pad, out, prob_threshold, objects16);
  308. proposals.insert(proposals.end(), objects16.begin(), objects16.end());
  309. }
  310. // stride 32
  311. {
  312. ncnn::Mat out;
  313. #if YOLOV5_V62
  314. ex.extract("367", out);
  315. #elif YOLOV5_V60
  316. ex.extract("401", out);
  317. #else
  318. ex.extract("801", out);
  319. #endif
  320. ncnn::Mat anchors(6);
  321. anchors[0] = 116.f;
  322. anchors[1] = 90.f;
  323. anchors[2] = 156.f;
  324. anchors[3] = 198.f;
  325. anchors[4] = 373.f;
  326. anchors[5] = 326.f;
  327. std::vector<Object> objects32;
  328. generate_proposals(anchors, 32, in_pad, out, prob_threshold, objects32);
  329. proposals.insert(proposals.end(), objects32.begin(), objects32.end());
  330. }
  331. // sort all proposals by score from highest to lowest
  332. qsort_descent_inplace(proposals);
  333. // apply nms with nms_threshold
  334. std::vector<int> picked;
  335. nms_sorted_bboxes(proposals, picked, nms_threshold);
  336. int count = picked.size();
  337. objects.resize(count);
  338. for (int i = 0; i < count; i++)
  339. {
  340. objects[i] = proposals[picked[i]];
  341. // adjust offset to original unpadded
  342. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  343. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  344. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  345. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  346. // clip
  347. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  348. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  349. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  350. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  351. objects[i].rect.x = x0;
  352. objects[i].rect.y = y0;
  353. objects[i].rect.width = x1 - x0;
  354. objects[i].rect.height = y1 - y0;
  355. }
  356. return 0;
  357. }
  358. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  359. {
  360. static const char* class_names[] = {
  361. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  362. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  363. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  364. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  365. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  366. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  367. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  368. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  369. "hair drier", "toothbrush"
  370. };
  371. cv::Mat image = bgr.clone();
  372. for (size_t i = 0; i < objects.size(); i++)
  373. {
  374. const Object& obj = objects[i];
  375. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  376. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  377. cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
  378. char text[256];
  379. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  380. int baseLine = 0;
  381. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  382. int x = obj.rect.x;
  383. int y = obj.rect.y - label_size.height - baseLine;
  384. if (y < 0)
  385. y = 0;
  386. if (x + label_size.width > image.cols)
  387. x = image.cols - label_size.width;
  388. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  389. cv::Scalar(255, 255, 255), -1);
  390. cv::putText(image, text, cv::Point(x, y + label_size.height),
  391. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  392. }
  393. cv::imshow("image", image);
  394. cv::waitKey(0);
  395. }
  396. int main(int argc, char** argv)
  397. {
  398. if (argc != 2)
  399. {
  400. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  401. return -1;
  402. }
  403. const char* imagepath = argv[1];
  404. cv::Mat m = cv::imread(imagepath, 1);
  405. if (m.empty())
  406. {
  407. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  408. return -1;
  409. }
  410. std::vector<Object> objects;
  411. detect_yolov5(m, objects);
  412. draw_objects(m, objects);
  413. return 0;
  414. }