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_pnnx.cpp 13 kB

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