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

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