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.cpp 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // Copyright (C) 2024 whyb(https://github.com/whyb). All rights reserved.
  6. //
  7. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  8. // in compliance with the License. You may obtain a copy of the License at
  9. //
  10. // https://opensource.org/licenses/BSD-3-Clause
  11. //
  12. // Unless required by applicable law or agreed to in writing, software distributed
  13. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  14. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations under the License.
  16. // ReadMe
  17. // Convert yolov8 model to ncnn model workflow:
  18. //
  19. // step 1:
  20. // If you don't want to train the model yourself. You should go to the ultralytics website download the pretrained model file.
  21. // original pretrained model from https://docs.ultralytics.com/models/yolov8/#supported-tasks-and-modes
  22. //
  23. // step 2:
  24. // run this command.
  25. // conda create --name yolov8 python=3.11
  26. // conda activate yolov8
  27. // pip install ultralytics onnx numpy protobuf
  28. //
  29. // step 3:
  30. // save source code file(export_model_to_ncnn.py):
  31. // from ultralytics import YOLO
  32. // detection_models = [
  33. // ["./Detection-pt/yolov8n.pt", "./Detection-pt/"],
  34. // ["./Detection-pt/yolov8s.pt", "./Detection-pt/"],
  35. // ["./Detection-pt/yolov8m.pt", "./Detection-pt/"],
  36. // ["./Detection-pt/yolov8l.pt", "./Detection-pt/"],
  37. // ["./Detection-pt/yolov8x.pt", "./Detection-pt/"]
  38. // ]
  39. // for model_dict in detection_models:
  40. // model = YOLO(model_dict[0]) # load an official pretrained weight model
  41. // model.export(format="ncnn", dynamic=True, save_dir=model_dict[1], simplify=True)
  42. //
  43. // step 4:
  44. // run command: python export_model_to_ncnn.py
  45. #include <memory>
  46. #include <vector>
  47. #include <algorithm>
  48. #include "layer.h"
  49. #include "net.h"
  50. #include <opencv2/opencv.hpp>
  51. #include <opencv2/core/core.hpp>
  52. #include <opencv2/highgui/highgui.hpp>
  53. #include <float.h>
  54. #include <stdio.h>
  55. #define MAX_STRIDE 32
  56. struct Object
  57. {
  58. cv::Rect_<float> rect;
  59. int label;
  60. float prob;
  61. };
  62. static inline float intersection_area(const Object& a, const Object& b)
  63. {
  64. cv::Rect_<float> inter = a.rect & b.rect;
  65. return inter.area();
  66. }
  67. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  68. {
  69. int i = left;
  70. int j = right;
  71. float p = objects[(left + right) / 2].prob;
  72. while (i <= j)
  73. {
  74. while (objects[i].prob > p)
  75. i++;
  76. while (objects[j].prob < p)
  77. j--;
  78. if (i <= j)
  79. {
  80. // swap
  81. std::swap(objects[i], objects[j]);
  82. i++;
  83. j--;
  84. }
  85. }
  86. #pragma omp parallel sections
  87. {
  88. #pragma omp section
  89. {
  90. if (left < j) qsort_descent_inplace(objects, left, j);
  91. }
  92. #pragma omp section
  93. {
  94. if (i < right) qsort_descent_inplace(objects, i, right);
  95. }
  96. }
  97. }
  98. static void qsort_descent_inplace(std::vector<Object>& objects)
  99. {
  100. if (objects.empty())
  101. return;
  102. qsort_descent_inplace(objects, 0, objects.size() - 1);
  103. }
  104. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  105. {
  106. picked.clear();
  107. const int n = faceobjects.size();
  108. std::vector<float> areas(n);
  109. for (int i = 0; i < n; i++)
  110. {
  111. areas[i] = faceobjects[i].rect.area();
  112. }
  113. for (int i = 0; i < n; i++)
  114. {
  115. const Object& a = faceobjects[i];
  116. int keep = 1;
  117. for (int j = 0; j < (int)picked.size(); j++)
  118. {
  119. const Object& b = faceobjects[picked[j]];
  120. if (!agnostic && a.label != b.label)
  121. continue;
  122. // intersection over union
  123. float inter_area = intersection_area(a, b);
  124. float union_area = areas[i] + areas[picked[j]] - inter_area;
  125. // float IoU = inter_area / union_area
  126. if (inter_area / union_area > nms_threshold)
  127. keep = 0;
  128. }
  129. if (keep)
  130. picked.push_back(i);
  131. }
  132. }
  133. static inline float sigmoid(float x)
  134. {
  135. return static_cast<float>(1.f / (1.f + exp(-x)));
  136. }
  137. static inline float clampf(float d, float min, float max)
  138. {
  139. const float t = d < min ? min : d;
  140. return t > max ? max : t;
  141. }
  142. static void parse_yolov8_detections(
  143. float* inputs, float confidence_threshold,
  144. int num_channels, int num_anchors, int num_labels,
  145. int infer_img_width, int infer_img_height,
  146. std::vector<Object>& objects)
  147. {
  148. std::vector<Object> detections;
  149. cv::Mat output = cv::Mat((int)num_channels, (int)num_anchors, CV_32F, inputs).t();
  150. for (int i = 0; i < num_anchors; i++)
  151. {
  152. const float* row_ptr = output.row(i).ptr<float>();
  153. const float* bboxes_ptr = row_ptr;
  154. const float* scores_ptr = row_ptr + 4;
  155. const float* max_s_ptr = std::max_element(scores_ptr, scores_ptr + num_labels);
  156. float score = *max_s_ptr;
  157. if (score > confidence_threshold)
  158. {
  159. float x = *bboxes_ptr++;
  160. float y = *bboxes_ptr++;
  161. float w = *bboxes_ptr++;
  162. float h = *bboxes_ptr;
  163. float x0 = clampf((x - 0.5f * w), 0.f, (float)infer_img_width);
  164. float y0 = clampf((y - 0.5f * h), 0.f, (float)infer_img_height);
  165. float x1 = clampf((x + 0.5f * w), 0.f, (float)infer_img_width);
  166. float y1 = clampf((y + 0.5f * h), 0.f, (float)infer_img_height);
  167. cv::Rect_<float> bbox;
  168. bbox.x = x0;
  169. bbox.y = y0;
  170. bbox.width = x1 - x0;
  171. bbox.height = y1 - y0;
  172. Object object;
  173. object.label = max_s_ptr - scores_ptr;
  174. object.prob = score;
  175. object.rect = bbox;
  176. detections.push_back(object);
  177. }
  178. }
  179. objects = detections;
  180. }
  181. static int detect_yolov8(const cv::Mat& bgr, std::vector<Object>& objects)
  182. {
  183. ncnn::Net yolov8;
  184. yolov8.opt.use_vulkan_compute = true; // if you want detect in hardware, then enable it
  185. yolov8.load_param("yolov8n.param");
  186. yolov8.load_model("yolov8n.bin");
  187. const int target_size = 640;
  188. const float prob_threshold = 0.25f;
  189. const float nms_threshold = 0.45f;
  190. int img_w = bgr.cols;
  191. int img_h = bgr.rows;
  192. // letterbox pad to multiple of MAX_STRIDE
  193. int w = img_w;
  194. int h = img_h;
  195. float scale = 1.f;
  196. if (w > h)
  197. {
  198. scale = (float)target_size / w;
  199. w = target_size;
  200. h = h * scale;
  201. }
  202. else
  203. {
  204. scale = (float)target_size / h;
  205. h = target_size;
  206. w = w * scale;
  207. }
  208. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
  209. int wpad = (target_size + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - w;
  210. int hpad = (target_size + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - h;
  211. ncnn::Mat in_pad;
  212. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
  213. const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
  214. in_pad.substract_mean_normalize(0, norm_vals);
  215. ncnn::Extractor ex = yolov8.create_extractor();
  216. ex.input("in0", in_pad);
  217. std::vector<Object> proposals;
  218. // stride 32
  219. {
  220. ncnn::Mat out;
  221. ex.extract("out0", out);
  222. std::vector<Object> objects32;
  223. const int num_labels = 80; // COCO has detect 80 object labels.
  224. parse_yolov8_detections(
  225. (float*)out.data, prob_threshold,
  226. out.h, out.w, num_labels,
  227. in_pad.w, in_pad.h,
  228. objects32);
  229. proposals.insert(proposals.end(), objects32.begin(), objects32.end());
  230. }
  231. // sort all proposals by score from highest to lowest
  232. qsort_descent_inplace(proposals);
  233. // apply nms with nms_threshold
  234. std::vector<int> picked;
  235. nms_sorted_bboxes(proposals, picked, nms_threshold);
  236. int count = picked.size();
  237. objects.resize(count);
  238. for (int i = 0; i < count; i++)
  239. {
  240. objects[i] = proposals[picked[i]];
  241. // adjust offset to original unpadded
  242. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  243. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  244. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  245. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  246. // clip
  247. x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  248. y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  249. x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  250. y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  251. objects[i].rect.x = x0;
  252. objects[i].rect.y = y0;
  253. objects[i].rect.width = x1 - x0;
  254. objects[i].rect.height = y1 - y0;
  255. }
  256. return 0;
  257. }
  258. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  259. {
  260. static const char* class_names[] = {
  261. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  262. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  263. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  264. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  265. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  266. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  267. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  268. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  269. "hair drier", "toothbrush"
  270. };
  271. static const unsigned char colors[19][3] = {
  272. {54, 67, 244},
  273. {99, 30, 233},
  274. {176, 39, 156},
  275. {183, 58, 103},
  276. {181, 81, 63},
  277. {243, 150, 33},
  278. {244, 169, 3},
  279. {212, 188, 0},
  280. {136, 150, 0},
  281. {80, 175, 76},
  282. {74, 195, 139},
  283. {57, 220, 205},
  284. {59, 235, 255},
  285. {7, 193, 255},
  286. {0, 152, 255},
  287. {34, 87, 255},
  288. {72, 85, 121},
  289. {158, 158, 158},
  290. {139, 125, 96}
  291. };
  292. int color_index = 0;
  293. cv::Mat image = bgr.clone();
  294. for (size_t i = 0; i < objects.size(); i++)
  295. {
  296. const Object& obj = objects[i];
  297. const unsigned char* color = colors[color_index % 19];
  298. color_index++;
  299. cv::Scalar cc(color[0], color[1], color[2]);
  300. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  301. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  302. cv::rectangle(image, obj.rect, cc, 2);
  303. char text[256];
  304. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  305. int baseLine = 0;
  306. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  307. int x = obj.rect.x;
  308. int y = obj.rect.y - label_size.height - baseLine;
  309. if (y < 0)
  310. y = 0;
  311. if (x + label_size.width > image.cols)
  312. x = image.cols - label_size.width;
  313. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  314. cc, -1);
  315. cv::putText(image, text, cv::Point(x, y + label_size.height),
  316. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255));
  317. }
  318. cv::imshow("image", image);
  319. cv::waitKey(0);
  320. }
  321. int main(int argc, char** argv)
  322. {
  323. if (argc != 2)
  324. {
  325. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  326. return -1;
  327. }
  328. const char* imagepath = argv[1];
  329. cv::Mat m = cv::imread(imagepath, 1);
  330. if (m.empty())
  331. {
  332. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  333. return -1;
  334. }
  335. std::vector<Object> objects;
  336. detect_yolov8(m, objects);
  337. draw_objects(m, objects);
  338. return 0;
  339. }