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

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