Elffuss BraidHub

kikocis/ncnn public

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