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.

yolov8_pose.cpp 17 kB

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