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.

yolov7.cpp 13 kB

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