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_pose.cpp 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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-pose torchscript
  6. // yolo export model=yolo11n-pose.pt format=torchscript
  7. // 3. convert torchscript with static shape
  8. // pnnx yolo11n-pose.torchscript
  9. // 4. modify yolo11n_pose_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_195 = v_194.view(1, 51, 6400)
  15. // v_201 = v_200.view(1, 51, 1600)
  16. // v_207 = v_206.view(1, 51, 400)
  17. // v_208 = torch.cat((v_195, v_201, v_207), dim=-1)
  18. // ...
  19. // v_254 = v_223.view(1, 65, 6400)
  20. // v_255 = v_238.view(1, 65, 1600)
  21. // v_256 = v_253.view(1, 65, 400)
  22. // v_257 = torch.cat((v_254, v_255, v_256), dim=2)
  23. // ...
  24. // after:
  25. // v_195 = v_194.view(1, 51, -1).transpose(1, 2)
  26. // v_201 = v_200.view(1, 51, -1).transpose(1, 2)
  27. // v_207 = v_206.view(1, 51, -1).transpose(1, 2)
  28. // v_208 = torch.cat((v_195, v_201, v_207), dim=1)
  29. // ...
  30. // v_254 = v_223.view(1, 65, -1).transpose(1, 2)
  31. // v_255 = v_238.view(1, 65, -1).transpose(1, 2)
  32. // v_256 = v_253.view(1, 65, -1).transpose(1, 2)
  33. // v_257 = torch.cat((v_254, v_255, v_256), dim=1)
  34. // return v_257, v_208
  35. // D. modify area attention for dynamic shape inference
  36. // before:
  37. // v_95 = self.model_10_m_0_attn_qkv_conv(v_94)
  38. // v_96 = v_95.view(1, 2, 128, 400)
  39. // v_97, v_98, v_99 = torch.split(tensor=v_96, dim=2, split_size_or_sections=(32,32,64))
  40. // v_100 = torch.transpose(input=v_97, dim0=-2, dim1=-1)
  41. // v_101 = torch.matmul(input=v_100, other=v_98)
  42. // v_102 = (v_101 * 0.176777)
  43. // v_103 = F.softmax(input=v_102, dim=-1)
  44. // v_104 = torch.transpose(input=v_103, dim0=-2, dim1=-1)
  45. // v_105 = torch.matmul(input=v_99, other=v_104)
  46. // v_106 = v_105.view(1, 128, 20, 20)
  47. // v_107 = v_99.reshape(1, 128, 20, 20)
  48. // v_108 = self.model_10_m_0_attn_pe_conv(v_107)
  49. // v_109 = (v_106 + v_108)
  50. // v_110 = self.model_10_m_0_attn_proj_conv(v_109)
  51. // after:
  52. // v_95 = self.model_10_m_0_attn_qkv_conv(v_94)
  53. // v_96 = v_95.view(1, 2, 128, -1)
  54. // v_97, v_98, v_99 = torch.split(tensor=v_96, dim=2, split_size_or_sections=(32,32,64))
  55. // v_100 = torch.transpose(input=v_97, dim0=-2, dim1=-1)
  56. // v_101 = torch.matmul(input=v_100, other=v_98)
  57. // v_102 = (v_101 * 0.176777)
  58. // v_103 = F.softmax(input=v_102, dim=-1)
  59. // v_104 = torch.transpose(input=v_103, dim0=-2, dim1=-1)
  60. // v_105 = torch.matmul(input=v_99, other=v_104)
  61. // v_106 = v_105.view(1, 128, v_95.size(2), v_95.size(3))
  62. // v_107 = v_99.reshape(1, 128, v_95.size(2), v_95.size(3))
  63. // v_108 = self.model_10_m_0_attn_pe_conv(v_107)
  64. // v_109 = (v_106 + v_108)
  65. // v_110 = self.model_10_m_0_attn_proj_conv(v_109)
  66. // 5. re-export yolo11-pose torchscript
  67. // python3 -c 'import yolo11n_pose_pnnx; yolo11n_pose_pnnx.export_torchscript()'
  68. // 6. convert new torchscript with dynamic shape
  69. // pnnx yolo11n_pose_pnnx.py.pt inputshape=[1,3,640,640] inputshape2=[1,3,320,320]
  70. // 7. now you get ncnn model files
  71. // mv yolo11n_pose_pnnx.py.ncnn.param yolo11n_pose.ncnn.param
  72. // mv yolo11n_pose_pnnx.py.ncnn.bin yolo11n_pose.ncnn.bin
  73. // the out blob would be a 2-dim tensor with w=65 h=8400
  74. //
  75. // | bbox-reg 16 x 4 |score(1)|
  76. // +-----+-----+-----+-----+--------+
  77. // | dx0 | dy0 | dx1 | dy1 | 0.1 |
  78. // all /| | | | | |
  79. // boxes | .. | .. | .. | .. | 0.0 |
  80. // (8400)| | | | | . |
  81. // \| | | | | . |
  82. // +-----+-----+-----+-----+--------+
  83. //
  84. //
  85. // | pose (51) |
  86. // +-----------+
  87. // |0.1........|
  88. // all /| |
  89. // boxes |0.0........|
  90. // (8400)| . |
  91. // \| . |
  92. // +-----------+
  93. //
  94. #include "layer.h"
  95. #include "net.h"
  96. #if defined(USE_NCNN_SIMPLEOCV)
  97. #include "simpleocv.h"
  98. #else
  99. #include <opencv2/core/core.hpp>
  100. #include <opencv2/highgui/highgui.hpp>
  101. #include <opencv2/imgproc/imgproc.hpp>
  102. #endif
  103. #include <float.h>
  104. #include <stdio.h>
  105. #include <vector>
  106. struct KeyPoint
  107. {
  108. cv::Point2f p;
  109. float prob;
  110. };
  111. struct Object
  112. {
  113. cv::Rect_<float> rect;
  114. int label;
  115. float prob;
  116. std::vector<KeyPoint> keypoints;
  117. };
  118. static inline float intersection_area(const Object& a, const Object& b)
  119. {
  120. cv::Rect_<float> inter = a.rect & b.rect;
  121. return inter.area();
  122. }
  123. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  124. {
  125. int i = left;
  126. int j = right;
  127. float p = objects[(left + right) / 2].prob;
  128. while (i <= j)
  129. {
  130. while (objects[i].prob > p)
  131. i++;
  132. while (objects[j].prob < p)
  133. j--;
  134. if (i <= j)
  135. {
  136. // swap
  137. std::swap(objects[i], objects[j]);
  138. i++;
  139. j--;
  140. }
  141. }
  142. // #pragma omp parallel sections
  143. {
  144. // #pragma omp section
  145. {
  146. if (left < j) qsort_descent_inplace(objects, left, j);
  147. }
  148. // #pragma omp section
  149. {
  150. if (i < right) qsort_descent_inplace(objects, i, right);
  151. }
  152. }
  153. }
  154. static void qsort_descent_inplace(std::vector<Object>& objects)
  155. {
  156. if (objects.empty())
  157. return;
  158. qsort_descent_inplace(objects, 0, objects.size() - 1);
  159. }
  160. static void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  161. {
  162. picked.clear();
  163. const int n = objects.size();
  164. std::vector<float> areas(n);
  165. for (int i = 0; i < n; i++)
  166. {
  167. areas[i] = objects[i].rect.area();
  168. }
  169. for (int i = 0; i < n; i++)
  170. {
  171. const Object& a = objects[i];
  172. int keep = 1;
  173. for (int j = 0; j < (int)picked.size(); j++)
  174. {
  175. const Object& b = objects[picked[j]];
  176. if (!agnostic && a.label != b.label)
  177. continue;
  178. // intersection over union
  179. float inter_area = intersection_area(a, b);
  180. float union_area = areas[i] + areas[picked[j]] - inter_area;
  181. // float IoU = inter_area / union_area
  182. if (inter_area / union_area > nms_threshold)
  183. keep = 0;
  184. }
  185. if (keep)
  186. picked.push_back(i);
  187. }
  188. }
  189. static inline float sigmoid(float x)
  190. {
  191. return 1.0f / (1.0f + expf(-x));
  192. }
  193. static void generate_proposals(const ncnn::Mat& pred, const ncnn::Mat& pred_points, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  194. {
  195. const int w = in_pad.w;
  196. const int h = in_pad.h;
  197. const int num_grid_x = w / stride;
  198. const int num_grid_y = h / stride;
  199. const int reg_max_1 = 16;
  200. const int num_points = pred_points.w / 3;
  201. for (int y = 0; y < num_grid_y; y++)
  202. {
  203. for (int x = 0; x < num_grid_x; x++)
  204. {
  205. const ncnn::Mat pred_grid = pred.row_range(y * num_grid_x + x, 1);
  206. const ncnn::Mat pred_points_grid = pred_points.row_range(y * num_grid_x + x, 1).reshape(3, num_points);
  207. // find label with max score
  208. int label = 0;
  209. float score = sigmoid(pred_grid[reg_max_1 * 4]);
  210. if (score >= prob_threshold)
  211. {
  212. ncnn::Mat pred_bbox = pred_grid.range(0, reg_max_1 * 4).reshape(reg_max_1, 4).clone();
  213. {
  214. ncnn::Layer* softmax = ncnn::create_layer("Softmax");
  215. ncnn::ParamDict pd;
  216. pd.set(0, 1); // axis
  217. pd.set(1, 1);
  218. softmax->load_param(pd);
  219. ncnn::Option opt;
  220. opt.num_threads = 1;
  221. opt.use_packing_layout = false;
  222. softmax->create_pipeline(opt);
  223. softmax->forward_inplace(pred_bbox, opt);
  224. softmax->destroy_pipeline(opt);
  225. delete softmax;
  226. }
  227. float pred_ltrb[4];
  228. for (int k = 0; k < 4; k++)
  229. {
  230. float dis = 0.f;
  231. const float* dis_after_sm = pred_bbox.row(k);
  232. for (int l = 0; l < reg_max_1; l++)
  233. {
  234. dis += l * dis_after_sm[l];
  235. }
  236. pred_ltrb[k] = dis * stride;
  237. }
  238. float pb_cx = (x + 0.5f) * stride;
  239. float pb_cy = (y + 0.5f) * stride;
  240. float x0 = pb_cx - pred_ltrb[0];
  241. float y0 = pb_cy - pred_ltrb[1];
  242. float x1 = pb_cx + pred_ltrb[2];
  243. float y1 = pb_cy + pred_ltrb[3];
  244. std::vector<KeyPoint> keypoints;
  245. for (int k = 0; k < num_points; k++)
  246. {
  247. KeyPoint keypoint;
  248. keypoint.p.x = (x + pred_points_grid.row(k)[0] * 2) * stride;
  249. keypoint.p.y = (y + pred_points_grid.row(k)[1] * 2) * stride;
  250. keypoint.prob = sigmoid(pred_points_grid.row(k)[2]);
  251. keypoints.push_back(keypoint);
  252. }
  253. Object obj;
  254. obj.rect.x = x0;
  255. obj.rect.y = y0;
  256. obj.rect.width = x1 - x0;
  257. obj.rect.height = y1 - y0;
  258. obj.label = label;
  259. obj.prob = score;
  260. obj.keypoints = keypoints;
  261. objects.push_back(obj);
  262. }
  263. }
  264. }
  265. }
  266. static void generate_proposals(const ncnn::Mat& pred, const ncnn::Mat& pred_points, const std::vector<int>& strides, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  267. {
  268. const int w = in_pad.w;
  269. const int h = in_pad.h;
  270. int pred_row_offset = 0;
  271. for (size_t i = 0; i < strides.size(); i++)
  272. {
  273. const int stride = strides[i];
  274. const int num_grid_x = w / stride;
  275. const int num_grid_y = h / stride;
  276. const int num_grid = num_grid_x * num_grid_y;
  277. generate_proposals(pred.row_range(pred_row_offset, num_grid), pred_points.row_range(pred_row_offset, num_grid), stride, in_pad, prob_threshold, objects);
  278. pred_row_offset += num_grid;
  279. }
  280. }
  281. static int detect_yolo11_pose(const cv::Mat& bgr, std::vector<Object>& objects)
  282. {
  283. ncnn::Net yolo11;
  284. yolo11.opt.use_vulkan_compute = true;
  285. // yolo11.opt.use_bf16_storage = true;
  286. // https://github.com/nihui/ncnn-android-yolo11/tree/master/app/src/main/assets
  287. yolo11.load_param("yolo11n_pose.ncnn.param");
  288. yolo11.load_model("yolo11n_pose.ncnn.bin");
  289. // yolo11.load_param("yolo11s_pose.ncnn.param");
  290. // yolo11.load_model("yolo11s_pose.ncnn.bin");
  291. // yolo11.load_param("yolo11m_pose.ncnn.param");
  292. // yolo11.load_model("yolo11m_pose.ncnn.bin");
  293. const int target_size = 640;
  294. const float prob_threshold = 0.25f;
  295. const float nms_threshold = 0.45f;
  296. const float mask_threshold = 0.5f;
  297. int img_w = bgr.cols;
  298. int img_h = bgr.rows;
  299. // ultralytics/cfg/models/v8/yolo11.yaml
  300. std::vector<int> strides(3);
  301. strides[0] = 8;
  302. strides[1] = 16;
  303. strides[2] = 32;
  304. const int max_stride = 32;
  305. // letterbox pad to multiple of max_stride
  306. int w = img_w;
  307. int h = img_h;
  308. float scale = 1.f;
  309. if (w > h)
  310. {
  311. scale = (float)target_size / w;
  312. w = target_size;
  313. h = h * scale;
  314. }
  315. else
  316. {
  317. scale = (float)target_size / h;
  318. h = target_size;
  319. w = w * scale;
  320. }
  321. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  322. // letterbox pad to target_size rectangle
  323. int wpad = (w + max_stride - 1) / max_stride * max_stride - w;
  324. int hpad = (h + max_stride - 1) / max_stride * max_stride - h;
  325. ncnn::Mat in_pad;
  326. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  327. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  328. in_pad.substract_mean_normalize(0, norm_vals);
  329. ncnn::Extractor ex = yolo11.create_extractor();
  330. ex.input("in0", in_pad);
  331. ncnn::Mat out;
  332. ex.extract("out0", out);
  333. ncnn::Mat out_points;
  334. ex.extract("out1", out_points);
  335. std::vector<Object> proposals;
  336. generate_proposals(out, out_points, strides, in_pad, prob_threshold, proposals);
  337. // sort all proposals by score from highest to lowest
  338. qsort_descent_inplace(proposals);
  339. // apply nms with nms_threshold
  340. std::vector<int> picked;
  341. nms_sorted_bboxes(proposals, picked, nms_threshold);
  342. int count = picked.size();
  343. if (count == 0)
  344. return 0;
  345. const int num_points = out_points.w / 3;
  346. objects.resize(count);
  347. for (int i = 0; i < count; i++)
  348. {
  349. objects[i] = proposals[picked[i]];
  350. // adjust offset to original unpadded
  351. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  352. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  353. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  354. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  355. for (int j = 0; j < num_points; j++)
  356. {
  357. objects[i].keypoints[j].p.x = (objects[i].keypoints[j].p.x - (wpad / 2)) / scale;
  358. objects[i].keypoints[j].p.y = (objects[i].keypoints[j].p.y - (hpad / 2)) / scale;
  359. }
  360. // clip
  361. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  362. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  363. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  364. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  365. objects[i].rect.x = x0;
  366. objects[i].rect.y = y0;
  367. objects[i].rect.width = x1 - x0;
  368. objects[i].rect.height = y1 - y0;
  369. }
  370. return 0;
  371. }
  372. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  373. {
  374. static const char* class_names[] = {"person"};
  375. static const cv::Scalar colors[] = {
  376. cv::Scalar(244, 67, 54),
  377. cv::Scalar(233, 30, 99),
  378. cv::Scalar(156, 39, 176),
  379. cv::Scalar(103, 58, 183),
  380. cv::Scalar(63, 81, 181),
  381. cv::Scalar(33, 150, 243),
  382. cv::Scalar(3, 169, 244),
  383. cv::Scalar(0, 188, 212),
  384. cv::Scalar(0, 150, 136),
  385. cv::Scalar(76, 175, 80),
  386. cv::Scalar(139, 195, 74),
  387. cv::Scalar(205, 220, 57),
  388. cv::Scalar(255, 235, 59),
  389. cv::Scalar(255, 193, 7),
  390. cv::Scalar(255, 152, 0),
  391. cv::Scalar(255, 87, 34),
  392. cv::Scalar(121, 85, 72),
  393. cv::Scalar(158, 158, 158),
  394. cv::Scalar(96, 125, 139)
  395. };
  396. cv::Mat image = bgr.clone();
  397. for (size_t i = 0; i < objects.size(); i++)
  398. {
  399. const Object& obj = objects[i];
  400. const cv::Scalar& color = colors[i % 19];
  401. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  402. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  403. // draw bone
  404. static const int joint_pairs[16][2] = {
  405. {0, 1}, {1, 3}, {0, 2}, {2, 4}, {5, 6}, {5, 7}, {7, 9}, {6, 8}, {8, 10}, {5, 11}, {6, 12}, {11, 12}, {11, 13}, {12, 14}, {13, 15}, {14, 16}
  406. };
  407. static const cv::Scalar bone_colors[] = {
  408. cv::Scalar(0, 255, 0),
  409. cv::Scalar(0, 255, 0),
  410. cv::Scalar(0, 255, 0),
  411. cv::Scalar(0, 255, 0),
  412. cv::Scalar(255, 128, 0),
  413. cv::Scalar(255, 128, 0),
  414. cv::Scalar(255, 128, 0),
  415. cv::Scalar(255, 128, 0),
  416. cv::Scalar(255, 128, 0),
  417. cv::Scalar(255, 51, 255),
  418. cv::Scalar(255, 51, 255),
  419. cv::Scalar(255, 51, 255),
  420. cv::Scalar(51, 153, 255),
  421. cv::Scalar(51, 153, 255),
  422. cv::Scalar(51, 153, 255),
  423. cv::Scalar(51, 153, 255),
  424. };
  425. for (int j = 0; j < 16; j++)
  426. {
  427. const KeyPoint& p1 = obj.keypoints[joint_pairs[j][0]];
  428. const KeyPoint& p2 = obj.keypoints[joint_pairs[j][1]];
  429. if (p1.prob < 0.2f || p2.prob < 0.2f)
  430. continue;
  431. cv::line(image, p1.p, p2.p, bone_colors[j], 2);
  432. }
  433. // draw joint
  434. for (size_t j = 0; j < obj.keypoints.size(); j++)
  435. {
  436. const KeyPoint& keypoint = obj.keypoints[j];
  437. fprintf(stderr, "%.2f %.2f = %.5f\n", keypoint.p.x, keypoint.p.y, keypoint.prob);
  438. if (keypoint.prob < 0.2f)
  439. continue;
  440. cv::circle(image, keypoint.p, 3, color, -1);
  441. }
  442. cv::rectangle(image, obj.rect, color);
  443. char text[256];
  444. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  445. int baseLine = 0;
  446. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  447. int x = obj.rect.x;
  448. int y = obj.rect.y - label_size.height - baseLine;
  449. if (y < 0)
  450. y = 0;
  451. if (x + label_size.width > image.cols)
  452. x = image.cols - label_size.width;
  453. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  454. cv::Scalar(255, 255, 255), -1);
  455. cv::putText(image, text, cv::Point(x, y + label_size.height),
  456. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  457. }
  458. cv::imshow("image", image);
  459. cv::waitKey(0);
  460. }
  461. int main(int argc, char** argv)
  462. {
  463. if (argc != 2)
  464. {
  465. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  466. return -1;
  467. }
  468. const char* imagepath = argv[1];
  469. cv::Mat m = cv::imread(imagepath, 1);
  470. if (m.empty())
  471. {
  472. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  473. return -1;
  474. }
  475. std::vector<Object> objects;
  476. detect_yolo11_pose(m, objects);
  477. draw_objects(m, objects);
  478. return 0;
  479. }