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

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