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

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