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.

yoloworld.cpp 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright 2025 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // 1. install
  4. // pip3 install -U ultralytics pnnx ncnn
  5. // 2. export yoloworld torchscript
  6. // yolo export model=yolov8s-world.pt format=torchscript
  7. // yolo export model=yolov8m-world.pt format=torchscript
  8. // yolo export model=yolov8l-world.pt format=torchscript
  9. // yolo export model=yolov8x-world.pt format=torchscript
  10. // yolo export model=yolov8s-worldv2.pt format=torchscript
  11. // yolo export model=yolov8m-worldv2.pt format=torchscript
  12. // yolo export model=yolov8l-worldv2.pt format=torchscript
  13. // yolo export model=yolov8x-worldv2.pt format=torchscript
  14. // 3. convert torchscript with static shape
  15. // pnnx yolov8s-world.torchscript
  16. // pnnx yolov8m-world.torchscript
  17. // pnnx yolov8l-world.torchscript
  18. // pnnx yolov8x-world.torchscript
  19. // pnnx yolov8s-worldv2.torchscript
  20. // pnnx yolov8m-worldv2.torchscript
  21. // pnnx yolov8l-worldv2.torchscript
  22. // pnnx yolov8x-worldv2.torchscript
  23. // the out blob would be a 2-dim tensor with w=8400 h=84
  24. //
  25. // | all boxes (8400) |
  26. // +-------------------------+
  27. // | center-x . |
  28. // bbox | center-y . |
  29. // | w . |
  30. // | h . |
  31. // +-------------------------+
  32. // | 0.1 . |
  33. // per | 0.0 . |
  34. // class | 0.5 . |
  35. // scores | . . |
  36. // (80) | . . |
  37. // +-------------------------+
  38. #include "layer.h"
  39. #include "net.h"
  40. #if defined(USE_NCNN_SIMPLEOCV)
  41. #include "simpleocv.h"
  42. #else
  43. #include <opencv2/core/core.hpp>
  44. #include <opencv2/highgui/highgui.hpp>
  45. #include <opencv2/imgproc/imgproc.hpp>
  46. #endif
  47. #include <float.h>
  48. #include <stdio.h>
  49. #include <vector>
  50. struct Object
  51. {
  52. cv::Rect_<float> rect;
  53. int label;
  54. float prob;
  55. };
  56. static inline float intersection_area(const Object& a, const Object& b)
  57. {
  58. cv::Rect_<float> inter = a.rect & b.rect;
  59. return inter.area();
  60. }
  61. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  62. {
  63. int i = left;
  64. int j = right;
  65. float p = objects[(left + right) / 2].prob;
  66. while (i <= j)
  67. {
  68. while (objects[i].prob > p)
  69. i++;
  70. while (objects[j].prob < p)
  71. j--;
  72. if (i <= j)
  73. {
  74. // swap
  75. std::swap(objects[i], objects[j]);
  76. i++;
  77. j--;
  78. }
  79. }
  80. // #pragma omp parallel sections
  81. {
  82. // #pragma omp section
  83. {
  84. if (left < j) qsort_descent_inplace(objects, left, j);
  85. }
  86. // #pragma omp section
  87. {
  88. if (i < right) qsort_descent_inplace(objects, i, right);
  89. }
  90. }
  91. }
  92. static void qsort_descent_inplace(std::vector<Object>& objects)
  93. {
  94. if (objects.empty())
  95. return;
  96. qsort_descent_inplace(objects, 0, objects.size() - 1);
  97. }
  98. static void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  99. {
  100. picked.clear();
  101. const int n = objects.size();
  102. std::vector<float> areas(n);
  103. for (int i = 0; i < n; i++)
  104. {
  105. areas[i] = objects[i].rect.area();
  106. }
  107. for (int i = 0; i < n; i++)
  108. {
  109. const Object& a = objects[i];
  110. int keep = 1;
  111. for (int j = 0; j < (int)picked.size(); j++)
  112. {
  113. const Object& b = objects[picked[j]];
  114. if (!agnostic && a.label != b.label)
  115. continue;
  116. // intersection over union
  117. float inter_area = intersection_area(a, b);
  118. float union_area = areas[i] + areas[picked[j]] - inter_area;
  119. // float IoU = inter_area / union_area
  120. if (inter_area / union_area > nms_threshold)
  121. keep = 0;
  122. }
  123. if (keep)
  124. picked.push_back(i);
  125. }
  126. }
  127. static void generate_proposals(const ncnn::Mat& pred, float prob_threshold, std::vector<Object>& objects)
  128. {
  129. const int num_boxes = pred.w;
  130. const int num_class = pred.h - 4;
  131. const ncnn::Mat pred_bbox = pred.row_range(0, 4);
  132. const ncnn::Mat pred_score = pred.row_range(4, num_class);
  133. for (int i = 0; i < num_boxes; i++)
  134. {
  135. int label = 0;
  136. float score = -9999.f;
  137. for (int j = 0; j < num_class; j++)
  138. {
  139. const float prob = pred_score.row(j)[i];
  140. if (prob > score)
  141. {
  142. score = prob;
  143. label = j;
  144. }
  145. }
  146. if (score >= prob_threshold)
  147. {
  148. const float cx = pred_bbox.row(0)[i];
  149. const float cy = pred_bbox.row(1)[i];
  150. const float w = pred_bbox.row(2)[i];
  151. const float h = pred_bbox.row(3)[i];
  152. Object obj;
  153. obj.rect.x = cx - w / 2;
  154. obj.rect.y = cy - h / 2;
  155. obj.rect.width = w;
  156. obj.rect.height = h;
  157. obj.label = label;
  158. obj.prob = score;
  159. objects.push_back(obj);
  160. }
  161. }
  162. }
  163. static int detect_yoloworld(const cv::Mat& bgr, std::vector<Object>& objects)
  164. {
  165. ncnn::Net yoloworld;
  166. yoloworld.opt.use_vulkan_compute = true;
  167. // yoloworld.opt.use_bf16_storage = true;
  168. // https://github.com/nihui/ncnn-assets/tree/master/models
  169. // yoloworld.load_param("yolov8s_world.ncnn.param");
  170. // yoloworld.load_model("yolov8s_world.ncnn.bin");
  171. // yoloworld.load_param("yolov8m_world.ncnn.param");
  172. // yoloworld.load_model("yolov8m_world.ncnn.bin");
  173. // yoloworld.load_param("yolov8l_world.ncnn.param");
  174. // yoloworld.load_model("yolov8l_world.ncnn.bin");
  175. // yoloworld.load_param("yolov8x_world.ncnn.param");
  176. // yoloworld.load_model("yolov8x_world.ncnn.bin");
  177. yoloworld.load_param("yolov8s_worldv2.ncnn.param");
  178. yoloworld.load_model("yolov8s_worldv2.ncnn.bin");
  179. // yoloworld.load_param("yolov8m_worldv2.ncnn.param");
  180. // yoloworld.load_model("yolov8m_worldv2.ncnn.bin");
  181. // yoloworld.load_param("yolov8l_worldv2.ncnn.param");
  182. // yoloworld.load_model("yolov8l_worldv2.ncnn.bin");
  183. // yoloworld.load_param("yolov8x_worldv2.ncnn.param");
  184. // yoloworld.load_model("yolov8x_worldv2.ncnn.bin");
  185. const int target_size = 640;
  186. const float prob_threshold = 0.25f;
  187. const float nms_threshold = 0.45f;
  188. int img_w = bgr.cols;
  189. int img_h = bgr.rows;
  190. // letterbox pad
  191. int w = img_w;
  192. int h = img_h;
  193. float scale = 1.f;
  194. if (w > h)
  195. {
  196. scale = (float)target_size / w;
  197. w = target_size;
  198. h = h * scale;
  199. }
  200. else
  201. {
  202. scale = (float)target_size / h;
  203. h = target_size;
  204. w = w * scale;
  205. }
  206. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  207. // letterbox pad to target_size rectangle
  208. int wpad = target_size - w;
  209. int hpad = target_size - h;
  210. ncnn::Mat in_pad;
  211. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  212. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  213. in_pad.substract_mean_normalize(0, norm_vals);
  214. ncnn::Extractor ex = yoloworld.create_extractor();
  215. ex.input("in0", in_pad);
  216. ncnn::Mat out;
  217. ex.extract("out0", out);
  218. std::vector<Object> proposals;
  219. generate_proposals(out, prob_threshold, proposals);
  220. // sort all proposals by score from highest to lowest
  221. qsort_descent_inplace(proposals);
  222. // apply nms with nms_threshold
  223. std::vector<int> picked;
  224. nms_sorted_bboxes(proposals, picked, nms_threshold);
  225. int count = picked.size();
  226. objects.resize(count);
  227. for (int i = 0; i < count; i++)
  228. {
  229. objects[i] = proposals[picked[i]];
  230. // adjust offset to original unpadded
  231. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  232. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  233. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  234. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  235. // clip
  236. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  237. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  238. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  239. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  240. objects[i].rect.x = x0;
  241. objects[i].rect.y = y0;
  242. objects[i].rect.width = x1 - x0;
  243. objects[i].rect.height = y1 - y0;
  244. }
  245. return 0;
  246. }
  247. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  248. {
  249. static const char* class_names[] = {
  250. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  251. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  252. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  253. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  254. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  255. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  256. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  257. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  258. "hair drier", "toothbrush"
  259. };
  260. static cv::Scalar colors[] = {
  261. cv::Scalar(244, 67, 54),
  262. cv::Scalar(233, 30, 99),
  263. cv::Scalar(156, 39, 176),
  264. cv::Scalar(103, 58, 183),
  265. cv::Scalar(63, 81, 181),
  266. cv::Scalar(33, 150, 243),
  267. cv::Scalar(3, 169, 244),
  268. cv::Scalar(0, 188, 212),
  269. cv::Scalar(0, 150, 136),
  270. cv::Scalar(76, 175, 80),
  271. cv::Scalar(139, 195, 74),
  272. cv::Scalar(205, 220, 57),
  273. cv::Scalar(255, 235, 59),
  274. cv::Scalar(255, 193, 7),
  275. cv::Scalar(255, 152, 0),
  276. cv::Scalar(255, 87, 34),
  277. cv::Scalar(121, 85, 72),
  278. cv::Scalar(158, 158, 158),
  279. cv::Scalar(96, 125, 139)
  280. };
  281. cv::Mat image = bgr.clone();
  282. for (size_t i = 0; i < objects.size(); i++)
  283. {
  284. const Object& obj = objects[i];
  285. const cv::Scalar& color = colors[i % 19];
  286. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  287. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  288. cv::rectangle(image, obj.rect, color);
  289. char text[256];
  290. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  291. int baseLine = 0;
  292. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  293. int x = obj.rect.x;
  294. int y = obj.rect.y - label_size.height - baseLine;
  295. if (y < 0)
  296. y = 0;
  297. if (x + label_size.width > image.cols)
  298. x = image.cols - label_size.width;
  299. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  300. cv::Scalar(255, 255, 255), -1);
  301. cv::putText(image, text, cv::Point(x, y + label_size.height),
  302. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  303. }
  304. cv::imshow("image", image);
  305. cv::waitKey(0);
  306. }
  307. int main(int argc, char** argv)
  308. {
  309. if (argc != 2)
  310. {
  311. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  312. return -1;
  313. }
  314. const char* imagepath = argv[1];
  315. cv::Mat m = cv::imread(imagepath, 1);
  316. if (m.empty())
  317. {
  318. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  319. return -1;
  320. }
  321. std::vector<Object> objects;
  322. detect_yoloworld(m, objects);
  323. draw_objects(m, objects);
  324. return 0;
  325. }