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.

yolo11.cpp 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. // Copyright 2025 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // 1. install
  4. // pip3 install -U ultralytics pnnx ncnn
  5. // 2. export yolo11 torchscript
  6. // yolo export model=yolo11n.pt format=torchscript
  7. // 3. convert torchscript with static shape
  8. // pnnx yolo11n.torchscript
  9. // 4. modify yolo11n_pnnx.py for dynamic shape inference
  10. // A. modify reshape to support dynamic image sizes
  11. // B. permute tensor before concat and adjust concat axis
  12. // C. drop post-process part
  13. // before:
  14. // v_235 = v_204.view(1, 144, 6400)
  15. // v_236 = v_219.view(1, 144, 1600)
  16. // v_237 = v_234.view(1, 144, 400)
  17. // v_238 = torch.cat((v_235, v_236, v_237), dim=2)
  18. // ...
  19. // after:
  20. // v_235 = v_204.view(1, 144, -1).transpose(1, 2)
  21. // v_236 = v_219.view(1, 144, -1).transpose(1, 2)
  22. // v_237 = v_234.view(1, 144, -1).transpose(1, 2)
  23. // v_238 = torch.cat((v_235, v_236, v_237), dim=1)
  24. // return v_238
  25. // D. modify area attention for dynamic shape inference
  26. // before:
  27. // v_95 = self.model_10_m_0_attn_qkv_conv(v_94)
  28. // v_96 = v_95.view(1, 2, 128, 400)
  29. // v_97, v_98, v_99 = torch.split(tensor=v_96, dim=2, split_size_or_sections=(32,32,64))
  30. // v_100 = torch.transpose(input=v_97, dim0=-2, dim1=-1)
  31. // v_101 = torch.matmul(input=v_100, other=v_98)
  32. // v_102 = (v_101 * 0.176777)
  33. // v_103 = F.softmax(input=v_102, dim=-1)
  34. // v_104 = torch.transpose(input=v_103, dim0=-2, dim1=-1)
  35. // v_105 = torch.matmul(input=v_99, other=v_104)
  36. // v_106 = v_105.view(1, 128, 20, 20)
  37. // v_107 = v_99.reshape(1, 128, 20, 20)
  38. // v_108 = self.model_10_m_0_attn_pe_conv(v_107)
  39. // v_109 = (v_106 + v_108)
  40. // v_110 = self.model_10_m_0_attn_proj_conv(v_109)
  41. // after:
  42. // v_95 = self.model_10_m_0_attn_qkv_conv(v_94)
  43. // v_96 = v_95.view(1, 2, 128, -1)
  44. // v_97, v_98, v_99 = torch.split(tensor=v_96, dim=2, split_size_or_sections=(32,32,64))
  45. // v_100 = torch.transpose(input=v_97, dim0=-2, dim1=-1)
  46. // v_101 = torch.matmul(input=v_100, other=v_98)
  47. // v_102 = (v_101 * 0.176777)
  48. // v_103 = F.softmax(input=v_102, dim=-1)
  49. // v_104 = torch.transpose(input=v_103, dim0=-2, dim1=-1)
  50. // v_105 = torch.matmul(input=v_99, other=v_104)
  51. // v_106 = v_105.view(1, 128, v_95.size(2), v_95.size(3))
  52. // v_107 = v_99.reshape(1, 128, v_95.size(2), v_95.size(3))
  53. // v_108 = self.model_10_m_0_attn_pe_conv(v_107)
  54. // v_109 = (v_106 + v_108)
  55. // v_110 = self.model_10_m_0_attn_proj_conv(v_109)
  56. // 5. re-export yolo11 torchscript
  57. // python3 -c 'import yolo11n_pnnx; yolo11n_pnnx.export_torchscript()'
  58. // 6. convert new torchscript with dynamic shape
  59. // pnnx yolo11n_pnnx.py.pt inputshape=[1,3,640,640] inputshape2=[1,3,320,320]
  60. // 7. now you get ncnn model files
  61. // mv yolo11n_pnnx.py.ncnn.param yolo11n.ncnn.param
  62. // mv yolo11n_pnnx.py.ncnn.bin yolo11n.ncnn.bin
  63. // the out blob would be a 2-dim tensor with w=144 h=8400
  64. //
  65. // | bbox-reg 16 x 4 | per-class scores(80) |
  66. // +-----+-----+-----+-----+----------------------+
  67. // | dx0 | dy0 | dx1 | dy1 |0.1 0.0 0.0 0.5 ......|
  68. // all /| | | | | . |
  69. // boxes | .. | .. | .. | .. |0.0 0.9 0.0 0.0 ......|
  70. // (8400)| | | | | . |
  71. // \| | | | | . |
  72. // +-----+-----+-----+-----+----------------------+
  73. //
  74. #include "layer.h"
  75. #include "net.h"
  76. #if defined(USE_NCNN_SIMPLEOCV)
  77. #include "simpleocv.h"
  78. #else
  79. #include <opencv2/core/core.hpp>
  80. #include <opencv2/highgui/highgui.hpp>
  81. #include <opencv2/imgproc/imgproc.hpp>
  82. #endif
  83. #include <float.h>
  84. #include <stdio.h>
  85. #include <vector>
  86. struct Object
  87. {
  88. cv::Rect_<float> rect;
  89. int label;
  90. float prob;
  91. };
  92. static inline float intersection_area(const Object& a, const Object& b)
  93. {
  94. cv::Rect_<float> inter = a.rect & b.rect;
  95. return inter.area();
  96. }
  97. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  98. {
  99. int i = left;
  100. int j = right;
  101. float p = objects[(left + right) / 2].prob;
  102. while (i <= j)
  103. {
  104. while (objects[i].prob > p)
  105. i++;
  106. while (objects[j].prob < p)
  107. j--;
  108. if (i <= j)
  109. {
  110. // swap
  111. std::swap(objects[i], objects[j]);
  112. i++;
  113. j--;
  114. }
  115. }
  116. // #pragma omp parallel sections
  117. {
  118. // #pragma omp section
  119. {
  120. if (left < j) qsort_descent_inplace(objects, left, j);
  121. }
  122. // #pragma omp section
  123. {
  124. if (i < right) qsort_descent_inplace(objects, i, right);
  125. }
  126. }
  127. }
  128. static void qsort_descent_inplace(std::vector<Object>& objects)
  129. {
  130. if (objects.empty())
  131. return;
  132. qsort_descent_inplace(objects, 0, objects.size() - 1);
  133. }
  134. static void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  135. {
  136. picked.clear();
  137. const int n = objects.size();
  138. std::vector<float> areas(n);
  139. for (int i = 0; i < n; i++)
  140. {
  141. areas[i] = objects[i].rect.area();
  142. }
  143. for (int i = 0; i < n; i++)
  144. {
  145. const Object& a = objects[i];
  146. int keep = 1;
  147. for (int j = 0; j < (int)picked.size(); j++)
  148. {
  149. const Object& b = objects[picked[j]];
  150. if (!agnostic && a.label != b.label)
  151. continue;
  152. // intersection over union
  153. float inter_area = intersection_area(a, b);
  154. float union_area = areas[i] + areas[picked[j]] - inter_area;
  155. // float IoU = inter_area / union_area
  156. if (inter_area / union_area > nms_threshold)
  157. keep = 0;
  158. }
  159. if (keep)
  160. picked.push_back(i);
  161. }
  162. }
  163. static inline float sigmoid(float x)
  164. {
  165. return 1.0f / (1.0f + expf(-x));
  166. }
  167. static void generate_proposals(const ncnn::Mat& pred, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  168. {
  169. const int w = in_pad.w;
  170. const int h = in_pad.h;
  171. const int num_grid_x = w / stride;
  172. const int num_grid_y = h / stride;
  173. const int reg_max_1 = 16;
  174. const int num_class = pred.w - reg_max_1 * 4; // number of classes. 80 for COCO
  175. for (int y = 0; y < num_grid_y; y++)
  176. {
  177. for (int x = 0; x < num_grid_x; x++)
  178. {
  179. const ncnn::Mat pred_grid = pred.row_range(y * num_grid_x + x, 1);
  180. // find label with max score
  181. int label = -1;
  182. float score = -FLT_MAX;
  183. {
  184. const ncnn::Mat pred_score = pred_grid.range(reg_max_1 * 4, num_class);
  185. for (int k = 0; k < num_class; k++)
  186. {
  187. float s = pred_score[k];
  188. if (s > score)
  189. {
  190. label = k;
  191. score = s;
  192. }
  193. }
  194. score = sigmoid(score);
  195. }
  196. if (score >= prob_threshold)
  197. {
  198. ncnn::Mat pred_bbox = pred_grid.range(0, reg_max_1 * 4).reshape(reg_max_1, 4);
  199. {
  200. ncnn::Layer* softmax = ncnn::create_layer("Softmax");
  201. ncnn::ParamDict pd;
  202. pd.set(0, 1); // axis
  203. pd.set(1, 1);
  204. softmax->load_param(pd);
  205. ncnn::Option opt;
  206. opt.num_threads = 1;
  207. opt.use_packing_layout = false;
  208. softmax->create_pipeline(opt);
  209. softmax->forward_inplace(pred_bbox, opt);
  210. softmax->destroy_pipeline(opt);
  211. delete softmax;
  212. }
  213. float pred_ltrb[4];
  214. for (int k = 0; k < 4; k++)
  215. {
  216. float dis = 0.f;
  217. const float* dis_after_sm = pred_bbox.row(k);
  218. for (int l = 0; l < reg_max_1; l++)
  219. {
  220. dis += l * dis_after_sm[l];
  221. }
  222. pred_ltrb[k] = dis * stride;
  223. }
  224. float pb_cx = (x + 0.5f) * stride;
  225. float pb_cy = (y + 0.5f) * stride;
  226. float x0 = pb_cx - pred_ltrb[0];
  227. float y0 = pb_cy - pred_ltrb[1];
  228. float x1 = pb_cx + pred_ltrb[2];
  229. float y1 = pb_cy + pred_ltrb[3];
  230. Object obj;
  231. obj.rect.x = x0;
  232. obj.rect.y = y0;
  233. obj.rect.width = x1 - x0;
  234. obj.rect.height = y1 - y0;
  235. obj.label = label;
  236. obj.prob = score;
  237. objects.push_back(obj);
  238. }
  239. }
  240. }
  241. }
  242. static void generate_proposals(const ncnn::Mat& pred, const std::vector<int>& strides, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  243. {
  244. const int w = in_pad.w;
  245. const int h = in_pad.h;
  246. int pred_row_offset = 0;
  247. for (size_t i = 0; i < strides.size(); i++)
  248. {
  249. const int stride = strides[i];
  250. const int num_grid_x = w / stride;
  251. const int num_grid_y = h / stride;
  252. const int num_grid = num_grid_x * num_grid_y;
  253. generate_proposals(pred.row_range(pred_row_offset, num_grid), stride, in_pad, prob_threshold, objects);
  254. pred_row_offset += num_grid;
  255. }
  256. }
  257. static int detect_yolo11(const cv::Mat& bgr, std::vector<Object>& objects)
  258. {
  259. ncnn::Net yolo11;
  260. yolo11.opt.use_vulkan_compute = true;
  261. // yolo11.opt.use_bf16_storage = true;
  262. // https://github.com/nihui/ncnn-android-yolo11/tree/master/app/src/main/assets
  263. yolo11.load_param("yolo11n.ncnn.param");
  264. yolo11.load_model("yolo11n.ncnn.bin");
  265. // yolo11.load_param("yolo11s.ncnn.param");
  266. // yolo11.load_model("yolo11s.ncnn.bin");
  267. // yolo11.load_param("yolo11m.ncnn.param");
  268. // yolo11.load_model("yolo11m.ncnn.bin");
  269. const int target_size = 640;
  270. const float prob_threshold = 0.25f;
  271. const float nms_threshold = 0.45f;
  272. int img_w = bgr.cols;
  273. int img_h = bgr.rows;
  274. // ultralytics/cfg/models/v8/yolo11.yaml
  275. std::vector<int> strides(3);
  276. strides[0] = 8;
  277. strides[1] = 16;
  278. strides[2] = 32;
  279. const int max_stride = 32;
  280. // letterbox pad to multiple of max_stride
  281. int w = img_w;
  282. int h = img_h;
  283. float scale = 1.f;
  284. if (w > h)
  285. {
  286. scale = (float)target_size / w;
  287. w = target_size;
  288. h = h * scale;
  289. }
  290. else
  291. {
  292. scale = (float)target_size / h;
  293. h = target_size;
  294. w = w * scale;
  295. }
  296. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  297. // letterbox pad to target_size rectangle
  298. int wpad = (w + max_stride - 1) / max_stride * max_stride - w;
  299. int hpad = (h + max_stride - 1) / max_stride * max_stride - h;
  300. ncnn::Mat in_pad;
  301. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  302. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  303. in_pad.substract_mean_normalize(0, norm_vals);
  304. ncnn::Extractor ex = yolo11.create_extractor();
  305. ex.input("in0", in_pad);
  306. ncnn::Mat out;
  307. ex.extract("out0", out);
  308. std::vector<Object> proposals;
  309. generate_proposals(out, strides, in_pad, prob_threshold, proposals);
  310. // sort all proposals by score from highest to lowest
  311. qsort_descent_inplace(proposals);
  312. // apply nms with nms_threshold
  313. std::vector<int> picked;
  314. nms_sorted_bboxes(proposals, picked, nms_threshold);
  315. int count = picked.size();
  316. objects.resize(count);
  317. for (int i = 0; i < count; i++)
  318. {
  319. objects[i] = proposals[picked[i]];
  320. // adjust offset to original unpadded
  321. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  322. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  323. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  324. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  325. // clip
  326. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  327. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  328. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  329. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  330. objects[i].rect.x = x0;
  331. objects[i].rect.y = y0;
  332. objects[i].rect.width = x1 - x0;
  333. objects[i].rect.height = y1 - y0;
  334. }
  335. return 0;
  336. }
  337. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  338. {
  339. static const char* class_names[] = {
  340. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  341. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  342. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  343. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  344. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  345. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  346. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  347. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  348. "hair drier", "toothbrush"
  349. };
  350. static cv::Scalar colors[] = {
  351. cv::Scalar(244, 67, 54),
  352. cv::Scalar(233, 30, 99),
  353. cv::Scalar(156, 39, 176),
  354. cv::Scalar(103, 58, 183),
  355. cv::Scalar(63, 81, 181),
  356. cv::Scalar(33, 150, 243),
  357. cv::Scalar(3, 169, 244),
  358. cv::Scalar(0, 188, 212),
  359. cv::Scalar(0, 150, 136),
  360. cv::Scalar(76, 175, 80),
  361. cv::Scalar(139, 195, 74),
  362. cv::Scalar(205, 220, 57),
  363. cv::Scalar(255, 235, 59),
  364. cv::Scalar(255, 193, 7),
  365. cv::Scalar(255, 152, 0),
  366. cv::Scalar(255, 87, 34),
  367. cv::Scalar(121, 85, 72),
  368. cv::Scalar(158, 158, 158),
  369. cv::Scalar(96, 125, 139)
  370. };
  371. cv::Mat image = bgr.clone();
  372. for (size_t i = 0; i < objects.size(); i++)
  373. {
  374. const Object& obj = objects[i];
  375. const cv::Scalar& color = colors[i % 19];
  376. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  377. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  378. cv::rectangle(image, obj.rect, color);
  379. char text[256];
  380. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  381. int baseLine = 0;
  382. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  383. int x = obj.rect.x;
  384. int y = obj.rect.y - label_size.height - baseLine;
  385. if (y < 0)
  386. y = 0;
  387. if (x + label_size.width > image.cols)
  388. x = image.cols - label_size.width;
  389. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  390. cv::Scalar(255, 255, 255), -1);
  391. cv::putText(image, text, cv::Point(x, y + label_size.height),
  392. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  393. }
  394. cv::imshow("image", image);
  395. cv::waitKey(0);
  396. }
  397. int main(int argc, char** argv)
  398. {
  399. if (argc != 2)
  400. {
  401. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  402. return -1;
  403. }
  404. const char* imagepath = argv[1];
  405. cv::Mat m = cv::imread(imagepath, 1);
  406. if (m.empty())
  407. {
  408. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  409. return -1;
  410. }
  411. std::vector<Object> objects;
  412. detect_yolo11(m, objects);
  413. draw_objects(m, objects);
  414. return 0;
  415. }