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

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