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

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