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_obb.cpp 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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-obb torchscript
  6. // yolo export model=yolo11n-obb.pt format=torchscript
  7. // 3. convert torchscript with static shape
  8. // pnnx yolo11n-obb.torchscript
  9. // 4. modify yolo11n_obb_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, 1, 16384)
  15. // v_201 = v_200.view(1, 1, 4096)
  16. // v_207 = v_206.view(1, 1, 1024)
  17. // v_208 = torch.cat((v_195, v_201, v_207), dim=2)
  18. // ...
  19. // v_256 = v_225.view(1, 79, 16384)
  20. // v_257 = v_240.view(1, 79, 4096)
  21. // v_258 = v_255.view(1, 79, 1024)
  22. // v_259 = torch.cat((v_256, v_257, v_258), dim=2)
  23. // ...
  24. // after:
  25. // v_195 = v_194.view(1, 1, -1).transpose(1, 2)
  26. // v_201 = v_200.view(1, 1, -1).transpose(1, 2)
  27. // v_207 = v_206.view(1, 1, -1).transpose(1, 2)
  28. // v_208 = torch.cat((v_195, v_201, v_207), dim=1)
  29. // ...
  30. // v_256 = v_225.view(1, 79, -1).transpose(1, 2)
  31. // v_257 = v_240.view(1, 79, -1).transpose(1, 2)
  32. // v_258 = v_255.view(1, 79, -1).transpose(1, 2)
  33. // v_259 = torch.cat((v_256, v_257, v_258), dim=1)
  34. // return v_259, 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, 1024)
  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, 32, 32)
  47. // v_107 = v_99.reshape(1, 128, 32, 32)
  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-obb torchscript
  67. // python3 -c 'import yolo11n_obb_pnnx; yolo11n_obb_pnnx.export_torchscript()'
  68. // 6. convert new torchscript with dynamic shape
  69. // pnnx yolo11n_obb_pnnx.py.pt inputshape=[1,3,1024,1024] inputshape2=[1,3,512,512]
  70. // 7. now you get ncnn model files
  71. // mv yolo11n_obb_pnnx.py.ncnn.param yolo11n_obb.ncnn.param
  72. // mv yolo11n_obb_pnnx.py.ncnn.bin yolo11n_obb.ncnn.bin
  73. // the out blob would be a 2-dim tensor with w=79 h=21504
  74. //
  75. // | bbox-reg 16 x 4 |score(15)|
  76. // +-----+-----+-----+-----+---------+
  77. // | dx0 | dy0 | dx1 | dy1 | 0.1 ... |
  78. // all /| | | | | ... |
  79. // boxes | .. | .. | .. | .. | 0.0 ... |
  80. // (21504)| | | | | . ... |
  81. // \| | | | | . ... |
  82. // +-----+-----+-----+-----+---------+
  83. //
  84. // the out blob would be a 2-dim tensor with w=1 h=21504
  85. //
  86. // | degree(1)|
  87. // +----------+
  88. // | 0.1 |
  89. // all /| |
  90. // boxes | 0.0 |
  91. // (21504)| . |
  92. // \| . |
  93. // +----------+
  94. //
  95. #include "layer.h"
  96. #include "net.h"
  97. #include <opencv2/core/core.hpp>
  98. #include <opencv2/highgui/highgui.hpp>
  99. #include <opencv2/imgproc/imgproc.hpp>
  100. #include <float.h>
  101. #include <math.h>
  102. #include <stdio.h>
  103. #include <vector>
  104. struct Object
  105. {
  106. cv::RotatedRect rrect;
  107. int label;
  108. float prob;
  109. };
  110. static inline float intersection_area(const Object& a, const Object& b)
  111. {
  112. std::vector<cv::Point2f> intersection;
  113. cv::rotatedRectangleIntersection(a.rrect, b.rrect, intersection);
  114. if (intersection.empty())
  115. return 0.f;
  116. return cv::contourArea(intersection);
  117. }
  118. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  119. {
  120. int i = left;
  121. int j = right;
  122. float p = objects[(left + right) / 2].prob;
  123. while (i <= j)
  124. {
  125. while (objects[i].prob > p)
  126. i++;
  127. while (objects[j].prob < p)
  128. j--;
  129. if (i <= j)
  130. {
  131. // swap
  132. std::swap(objects[i], objects[j]);
  133. i++;
  134. j--;
  135. }
  136. }
  137. // #pragma omp parallel sections
  138. {
  139. // #pragma omp section
  140. {
  141. if (left < j) qsort_descent_inplace(objects, left, j);
  142. }
  143. // #pragma omp section
  144. {
  145. if (i < right) qsort_descent_inplace(objects, i, right);
  146. }
  147. }
  148. }
  149. static void qsort_descent_inplace(std::vector<Object>& objects)
  150. {
  151. if (objects.empty())
  152. return;
  153. qsort_descent_inplace(objects, 0, objects.size() - 1);
  154. }
  155. static void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  156. {
  157. picked.clear();
  158. const int n = objects.size();
  159. std::vector<float> areas(n);
  160. for (int i = 0; i < n; i++)
  161. {
  162. areas[i] = objects[i].rrect.size.area();
  163. }
  164. for (int i = 0; i < n; i++)
  165. {
  166. const Object& a = objects[i];
  167. int keep = 1;
  168. for (int j = 0; j < (int)picked.size(); j++)
  169. {
  170. const Object& b = objects[picked[j]];
  171. if (!agnostic && a.label != b.label)
  172. continue;
  173. // intersection over union
  174. float inter_area = intersection_area(a, b);
  175. float union_area = areas[i] + areas[picked[j]] - inter_area;
  176. // float IoU = inter_area / union_area;
  177. if (inter_area / union_area > nms_threshold)
  178. keep = 0;
  179. }
  180. if (keep)
  181. picked.push_back(i);
  182. }
  183. }
  184. static inline float sigmoid(float x)
  185. {
  186. return 1.0f / (1.0f + expf(-x));
  187. }
  188. static void generate_proposals(const ncnn::Mat& pred, const ncnn::Mat& pred_angle, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  189. {
  190. const int w = in_pad.w;
  191. const int h = in_pad.h;
  192. const int num_grid_x = w / stride;
  193. const int num_grid_y = h / stride;
  194. const int reg_max_1 = 16;
  195. const int num_class = pred.w - reg_max_1 * 4; // number of classes. 15 for DOTAv1
  196. for (int y = 0; y < num_grid_y; y++)
  197. {
  198. for (int x = 0; x < num_grid_x; x++)
  199. {
  200. const ncnn::Mat pred_grid = pred.row_range(y * num_grid_x + x, 1);
  201. // find label with max score
  202. int label = -1;
  203. float score = -FLT_MAX;
  204. {
  205. const ncnn::Mat pred_score = pred_grid.range(reg_max_1 * 4, num_class);
  206. for (int k = 0; k < num_class; k++)
  207. {
  208. float s = pred_score[k];
  209. if (s > score)
  210. {
  211. label = k;
  212. score = s;
  213. }
  214. }
  215. score = sigmoid(score);
  216. }
  217. if (score >= prob_threshold)
  218. {
  219. ncnn::Mat pred_bbox = pred_grid.range(0, reg_max_1 * 4).reshape(reg_max_1, 4).clone();
  220. {
  221. ncnn::Layer* softmax = ncnn::create_layer("Softmax");
  222. ncnn::ParamDict pd;
  223. pd.set(0, 1); // axis
  224. pd.set(1, 1);
  225. softmax->load_param(pd);
  226. ncnn::Option opt;
  227. opt.num_threads = 1;
  228. opt.use_packing_layout = false;
  229. softmax->create_pipeline(opt);
  230. softmax->forward_inplace(pred_bbox, opt);
  231. softmax->destroy_pipeline(opt);
  232. delete softmax;
  233. }
  234. float pred_ltrb[4];
  235. for (int k = 0; k < 4; k++)
  236. {
  237. float dis = 0.f;
  238. const float* dis_after_sm = pred_bbox.row(k);
  239. for (int l = 0; l < reg_max_1; l++)
  240. {
  241. dis += l * dis_after_sm[l];
  242. }
  243. pred_ltrb[k] = dis * stride;
  244. }
  245. float pb_cx = (x + 0.5f) * stride;
  246. float pb_cy = (y + 0.5f) * stride;
  247. const float angle = sigmoid(pred_angle.row(y * num_grid_x + x)[0]) - 0.25f;
  248. const float angle_rad = angle * 3.14159265358979323846f;
  249. const float angle_degree = angle * 180.f;
  250. float cos = cosf(angle_rad);
  251. float sin = sinf(angle_rad);
  252. float xx = (pred_ltrb[2] - pred_ltrb[0]) * 0.5f;
  253. float yy = (pred_ltrb[3] - pred_ltrb[1]) * 0.5f;
  254. float xr = xx * cos - yy * sin;
  255. float yr = xx * sin + yy * cos;
  256. const float cx = pb_cx + xr;
  257. const float cy = pb_cy + yr;
  258. const float ww = pred_ltrb[2] + pred_ltrb[0];
  259. const float hh = pred_ltrb[3] + pred_ltrb[1];
  260. Object obj;
  261. obj.rrect = cv::RotatedRect(cv::Point2f(cx, cy), cv::Size_<float>(ww, hh), angle_degree);
  262. obj.label = label;
  263. obj.prob = score;
  264. objects.push_back(obj);
  265. }
  266. }
  267. }
  268. }
  269. static void generate_proposals(const ncnn::Mat& pred, const ncnn::Mat& pred_angle, const std::vector<int>& strides, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  270. {
  271. const int w = in_pad.w;
  272. const int h = in_pad.h;
  273. int pred_row_offset = 0;
  274. for (size_t i = 0; i < strides.size(); i++)
  275. {
  276. const int stride = strides[i];
  277. const int num_grid_x = w / stride;
  278. const int num_grid_y = h / stride;
  279. const int num_grid = num_grid_x * num_grid_y;
  280. generate_proposals(pred.row_range(pred_row_offset, num_grid), pred_angle.row_range(pred_row_offset, num_grid), stride, in_pad, prob_threshold, objects);
  281. pred_row_offset += num_grid;
  282. }
  283. }
  284. static int detect_yolo11_obb(const cv::Mat& bgr, std::vector<Object>& objects)
  285. {
  286. ncnn::Net yolo11;
  287. yolo11.opt.use_vulkan_compute = true;
  288. // yolo11.opt.use_bf16_storage = true;
  289. // https://github.com/nihui/ncnn-android-yolo11/tree/master/app/src/main/assets
  290. yolo11.load_param("yolo11n_obb.ncnn.param");
  291. yolo11.load_model("yolo11n_obb.ncnn.bin");
  292. // yolo11.load_param("yolo11s_obb.ncnn.param");
  293. // yolo11.load_model("yolo11s_obb.ncnn.bin");
  294. // yolo11.load_param("yolo11m_obb.ncnn.param");
  295. // yolo11.load_model("yolo11m_obb.ncnn.bin");
  296. const int target_size = 1024;
  297. const float prob_threshold = 0.25f;
  298. const float nms_threshold = 0.45f;
  299. int img_w = bgr.cols;
  300. int img_h = bgr.rows;
  301. // ultralytics/cfg/models/v8/yolo11.yaml
  302. std::vector<int> strides(3);
  303. strides[0] = 8;
  304. strides[1] = 16;
  305. strides[2] = 32;
  306. const int max_stride = 32;
  307. // letterbox pad to multiple of max_stride
  308. int w = img_w;
  309. int h = img_h;
  310. float scale = 1.f;
  311. if (w > h)
  312. {
  313. scale = (float)target_size / w;
  314. w = target_size;
  315. h = h * scale;
  316. }
  317. else
  318. {
  319. scale = (float)target_size / h;
  320. h = target_size;
  321. w = w * scale;
  322. }
  323. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  324. // letterbox pad to target_size rectangle
  325. int wpad = (w + max_stride - 1) / max_stride * max_stride - w;
  326. int hpad = (h + max_stride - 1) / max_stride * max_stride - h;
  327. ncnn::Mat in_pad;
  328. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  329. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  330. in_pad.substract_mean_normalize(0, norm_vals);
  331. ncnn::Extractor ex = yolo11.create_extractor();
  332. ex.input("in0", in_pad);
  333. ncnn::Mat out;
  334. ex.extract("out0", out);
  335. ncnn::Mat out_angle;
  336. ex.extract("out1", out_angle);
  337. std::vector<Object> proposals;
  338. generate_proposals(out, out_angle, strides, in_pad, prob_threshold, proposals);
  339. // sort all proposals by score from highest to lowest
  340. qsort_descent_inplace(proposals);
  341. // apply nms with nms_threshold
  342. std::vector<int> picked;
  343. nms_sorted_bboxes(proposals, picked, nms_threshold);
  344. int count = picked.size();
  345. if (count == 0)
  346. return 0;
  347. objects.resize(count);
  348. for (int i = 0; i < count; i++)
  349. {
  350. Object obj = proposals[picked[i]];
  351. // adjust offset to original unpadded
  352. obj.rrect.center.x = (obj.rrect.center.x - (wpad / 2)) / scale;
  353. obj.rrect.center.y = (obj.rrect.center.y - (hpad / 2)) / scale;
  354. obj.rrect.size.width = (obj.rrect.size.width) / scale;
  355. obj.rrect.size.height = (obj.rrect.size.height) / scale;
  356. objects[i] = obj;
  357. }
  358. return 0;
  359. }
  360. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  361. {
  362. static const char* class_names[] = {
  363. "plane", "ship", "storage tank", "baseball diamond", "tennis court",
  364. "basketball court", "ground track field", "harbor", "bridge", "large vehicle",
  365. "small vehicle", "helicopter", "roundabout", "soccer ball field", "swimming pool"
  366. };
  367. static const cv::Scalar colors[] = {
  368. cv::Scalar(156, 39, 176),
  369. cv::Scalar(103, 58, 183),
  370. cv::Scalar(63, 81, 181),
  371. cv::Scalar(33, 150, 243),
  372. cv::Scalar(3, 169, 244),
  373. cv::Scalar(0, 188, 212),
  374. cv::Scalar(0, 150, 136),
  375. cv::Scalar(76, 175, 80),
  376. cv::Scalar(139, 195, 74),
  377. cv::Scalar(205, 220, 57),
  378. cv::Scalar(255, 235, 59),
  379. cv::Scalar(255, 193, 7),
  380. cv::Scalar(255, 152, 0),
  381. cv::Scalar(255, 87, 34),
  382. cv::Scalar(121, 85, 72),
  383. cv::Scalar(158, 158, 158),
  384. cv::Scalar(96, 125, 139)
  385. };
  386. cv::Mat image = bgr.clone();
  387. for (size_t i = 0; i < objects.size(); i++)
  388. {
  389. const Object& obj = objects[i];
  390. const cv::Scalar& color = colors[obj.label];
  391. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f @ %.2f\n", obj.label, obj.prob,
  392. obj.rrect.center.x, obj.rrect.center.y, obj.rrect.size.width, obj.rrect.size.height, obj.rrect.angle);
  393. cv::Point2f corners[4];
  394. obj.rrect.points(corners);
  395. cv::line(image, corners[0], corners[1], color);
  396. cv::line(image, corners[1], corners[2], color);
  397. cv::line(image, corners[2], corners[3], color);
  398. cv::line(image, corners[3], corners[0], color);
  399. }
  400. for (size_t i = 0; i < objects.size(); i++)
  401. {
  402. const Object& obj = objects[i];
  403. const cv::Scalar& color = colors[obj.label];
  404. char text[256];
  405. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  406. int baseLine = 0;
  407. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  408. int x = obj.rrect.center.x - label_size.width / 2;
  409. int y = obj.rrect.center.y - label_size.height / 2 - baseLine;
  410. if (y < 0)
  411. y = 0;
  412. if (y + label_size.height > image.rows)
  413. y = image.rows - label_size.height;
  414. if (x < 0)
  415. x = 0;
  416. if (x + label_size.width > image.cols)
  417. x = image.cols - label_size.width;
  418. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  419. cv::Scalar(255, 255, 255), -1);
  420. cv::putText(image, text, cv::Point(x, y + label_size.height),
  421. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  422. }
  423. cv::imshow("image", image);
  424. cv::waitKey(0);
  425. }
  426. int main(int argc, char** argv)
  427. {
  428. if (argc != 2)
  429. {
  430. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  431. return -1;
  432. }
  433. const char* imagepath = argv[1];
  434. cv::Mat m = cv::imread(imagepath, 1);
  435. if (m.empty())
  436. {
  437. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  438. return -1;
  439. }
  440. std::vector<Object> objects;
  441. detect_yolo11_obb(m, objects);
  442. draw_objects(m, objects);
  443. return 0;
  444. }