Elffuss BraidHub

kikocis/ncnn public

master · 15.1 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "layer.h"
16#include "net.h"
17
18#if defined(USE_NCNN_SIMPLEOCV)
19#include "simpleocv.h"
20#else
21#include <opencv2/core/core.hpp>
22#include <opencv2/highgui/highgui.hpp>
23#include <opencv2/imgproc/imgproc.hpp>
24#endif
25#include <float.h>
26#include <stdio.h>
27#include <vector>
28
29//#define YOLOV5_V60 1 //YOLOv5 v6.0
30#define YOLOV5_V62 1 //YOLOv5 v6.2 export onnx model method https://github.com/shaoshengsong/yolov5_62_export_ncnn
31
32#if YOLOV5_V60 || YOLOV5_V62
33#define MAX_STRIDE 64
34#else
35#define MAX_STRIDE 32
36class YoloV5Focus : public ncnn::Layer
37{
38public:
39 YoloV5Focus()
40 {
41 one_blob_only = true;
42 }
43
44 virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
45 {
46 int w = bottom_blob.w;
47 int h = bottom_blob.h;
48 int channels = bottom_blob.c;
49
50 int outw = w / 2;
51 int outh = h / 2;
52 int outc = channels * 4;
53
54 top_blob.create(outw, outh, outc, 4u, 1, opt.blob_allocator);
55 if (top_blob.empty())
56 return -100;
57
58 #pragma omp parallel for num_threads(opt.num_threads)
59 for (int p = 0; p < outc; p++)
60 {
61 const float* ptr = bottom_blob.channel(p % channels).row((p / channels) % 2) + ((p / channels) / 2);
62 float* outptr = top_blob.channel(p);
63
64 for (int i = 0; i < outh; i++)
65 {
66 for (int j = 0; j < outw; j++)
67 {
68 *outptr = *ptr;
69
70 outptr += 1;
71 ptr += 2;
72 }
73
74 ptr += w;
75 }
76 }
77
78 return 0;
79 }
80};
81
82DEFINE_LAYER_CREATOR(YoloV5Focus)
83#endif //YOLOV5_V60 YOLOV5_V62
84
85struct Object
86{
87 cv::Rect_<float> rect;
88 int label;
89 float prob;
90};
91
92static inline float intersection_area(const Object& a, const Object& b)
93{
94 cv::Rect_<float> inter = a.rect & b.rect;
95 return inter.area();
96}
97
98static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
99{
100 int i = left;
101 int j = right;
102 float p = faceobjects[(left + right) / 2].prob;
103
104 while (i <= j)
105 {
106 while (faceobjects[i].prob > p)
107 i++;
108
109 while (faceobjects[j].prob < p)
110 j--;
111
112 if (i <= j)
113 {
114 // swap
115 std::swap(faceobjects[i], faceobjects[j]);
116
117 i++;
118 j--;
119 }
120 }
121
122 #pragma omp parallel sections
123 {
124 #pragma omp section
125 {
126 if (left < j) qsort_descent_inplace(faceobjects, left, j);
127 }
128 #pragma omp section
129 {
130 if (i < right) qsort_descent_inplace(faceobjects, i, right);
131 }
132 }
133}
134
135static void qsort_descent_inplace(std::vector<Object>& faceobjects)
136{
137 if (faceobjects.empty())
138 return;
139
140 qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
141}
142
143static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
144{
145 picked.clear();
146
147 const int n = faceobjects.size();
148
149 std::vector<float> areas(n);
150 for (int i = 0; i < n; i++)
151 {
152 areas[i] = faceobjects[i].rect.area();
153 }
154
155 for (int i = 0; i < n; i++)
156 {
157 const Object& a = faceobjects[i];
158
159 int keep = 1;
160 for (int j = 0; j < (int)picked.size(); j++)
161 {
162 const Object& b = faceobjects[picked[j]];
163
164 if (!agnostic && a.label != b.label)
165 continue;
166
167 // intersection over union
168 float inter_area = intersection_area(a, b);
169 float union_area = areas[i] + areas[picked[j]] - inter_area;
170 // float IoU = inter_area / union_area
171 if (inter_area / union_area > nms_threshold)
172 keep = 0;
173 }
174
175 if (keep)
176 picked.push_back(i);
177 }
178}
179
180static inline float sigmoid(float x)
181{
182 return static_cast<float>(1.f / (1.f + exp(-x)));
183}
184
185static void generate_proposals(const ncnn::Mat& anchors, int stride, const ncnn::Mat& in_pad, const ncnn::Mat& feat_blob, float prob_threshold, std::vector<Object>& objects)
186{
187 const int num_grid = feat_blob.h;
188
189 int num_grid_x;
190 int num_grid_y;
191 if (in_pad.w > in_pad.h)
192 {
193 num_grid_x = in_pad.w / stride;
194 num_grid_y = num_grid / num_grid_x;
195 }
196 else
197 {
198 num_grid_y = in_pad.h / stride;
199 num_grid_x = num_grid / num_grid_y;
200 }
201
202 const int num_class = feat_blob.w - 5;
203
204 const int num_anchors = anchors.w / 2;
205
206 for (int q = 0; q < num_anchors; q++)
207 {
208 const float anchor_w = anchors[q * 2];
209 const float anchor_h = anchors[q * 2 + 1];
210
211 const ncnn::Mat feat = feat_blob.channel(q);
212
213 for (int i = 0; i < num_grid_y; i++)
214 {
215 for (int j = 0; j < num_grid_x; j++)
216 {
217 const float* featptr = feat.row(i * num_grid_x + j);
218 float box_confidence = sigmoid(featptr[4]);
219 if (box_confidence >= prob_threshold)
220 {
221 // find class index with max class score
222 int class_index = 0;
223 float class_score = -FLT_MAX;
224 for (int k = 0; k < num_class; k++)
225 {
226 float score = featptr[5 + k];
227 if (score > class_score)
228 {
229 class_index = k;
230 class_score = score;
231 }
232 }
233 float confidence = box_confidence * sigmoid(class_score);
234 if (confidence >= prob_threshold)
235 {
236 // yolov5/models/yolo.py Detect forward
237 // y = x[i].sigmoid()
238 // y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
239 // y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
240
241 float dx = sigmoid(featptr[0]);
242 float dy = sigmoid(featptr[1]);
243 float dw = sigmoid(featptr[2]);
244 float dh = sigmoid(featptr[3]);
245
246 float pb_cx = (dx * 2.f - 0.5f + j) * stride;
247 float pb_cy = (dy * 2.f - 0.5f + i) * stride;
248
249 float pb_w = pow(dw * 2.f, 2) * anchor_w;
250 float pb_h = pow(dh * 2.f, 2) * anchor_h;
251
252 float x0 = pb_cx - pb_w * 0.5f;
253 float y0 = pb_cy - pb_h * 0.5f;
254 float x1 = pb_cx + pb_w * 0.5f;
255 float y1 = pb_cy + pb_h * 0.5f;
256
257 Object obj;
258 obj.rect.x = x0;
259 obj.rect.y = y0;
260 obj.rect.width = x1 - x0;
261 obj.rect.height = y1 - y0;
262 obj.label = class_index;
263 obj.prob = confidence;
264
265 objects.push_back(obj);
266 }
267 }
268 }
269 }
270 }
271}
272
273static int detect_yolov5(const cv::Mat& bgr, std::vector<Object>& objects)
274{
275 ncnn::Net yolov5;
276
277 yolov5.opt.use_vulkan_compute = true;
278 // yolov5.opt.use_bf16_storage = true;
279
280 // original pretrained model from https://github.com/ultralytics/yolov5
281 // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
282#if YOLOV5_V62
283 if (yolov5.load_param("yolov5s_6.2.param"))
284 exit(-1);
285 if (yolov5.load_model("yolov5s_6.2.bin"))
286 exit(-1);
287#elif YOLOV5_V60
288 if (yolov5.load_param("yolov5s_6.0.param"))
289 exit(-1);
290 if (yolov5.load_model("yolov5s_6.0.bin"))
291 exit(-1);
292#else
293 yolov5.register_custom_layer("YoloV5Focus", YoloV5Focus_layer_creator);
294
295 if (yolov5.load_param("yolov5s.param"))
296 exit(-1);
297 if (yolov5.load_model("yolov5s.bin"))
298 exit(-1);
299#endif
300
301 const int target_size = 640;
302 const float prob_threshold = 0.25f;
303 const float nms_threshold = 0.45f;
304
305 int img_w = bgr.cols;
306 int img_h = bgr.rows;
307
308 // letterbox pad to multiple of MAX_STRIDE
309 int w = img_w;
310 int h = img_h;
311 float scale = 1.f;
312 if (w > h)
313 {
314 scale = (float)target_size / w;
315 w = target_size;
316 h = h * scale;
317 }
318 else
319 {
320 scale = (float)target_size / h;
321 h = target_size;
322 w = w * scale;
323 }
324
325 ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
326
327 // pad to target_size rectangle
328 // yolov5/utils/datasets.py letterbox
329 int wpad = (w + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - w;
330 int hpad = (h + MAX_STRIDE - 1) / MAX_STRIDE * MAX_STRIDE - h;
331 ncnn::Mat in_pad;
332 ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
333
334 const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f};
335 in_pad.substract_mean_normalize(0, norm_vals);
336
337 ncnn::Extractor ex = yolov5.create_extractor();
338
339 ex.input("images", in_pad);
340
341 std::vector<Object> proposals;
342
343 // anchor setting from yolov5/models/yolov5s.yaml
344
345 // stride 8
346 {
347 ncnn::Mat out;
348 ex.extract("output", out);
349
350 ncnn::Mat anchors(6);
351 anchors[0] = 10.f;
352 anchors[1] = 13.f;
353 anchors[2] = 16.f;
354 anchors[3] = 30.f;
355 anchors[4] = 33.f;
356 anchors[5] = 23.f;
357
358 std::vector<Object> objects8;
359 generate_proposals(anchors, 8, in_pad, out, prob_threshold, objects8);
360
361 proposals.insert(proposals.end(), objects8.begin(), objects8.end());
362 }
363
364 // stride 16
365 {
366 ncnn::Mat out;
367
368#if YOLOV5_V62
369 ex.extract("353", out);
370#elif YOLOV5_V60
371 ex.extract("376", out);
372#else
373 ex.extract("781", out);
374#endif
375
376 ncnn::Mat anchors(6);
377 anchors[0] = 30.f;
378 anchors[1] = 61.f;
379 anchors[2] = 62.f;
380 anchors[3] = 45.f;
381 anchors[4] = 59.f;
382 anchors[5] = 119.f;
383
384 std::vector<Object> objects16;
385 generate_proposals(anchors, 16, in_pad, out, prob_threshold, objects16);
386
387 proposals.insert(proposals.end(), objects16.begin(), objects16.end());
388 }
389
390 // stride 32
391 {
392 ncnn::Mat out;
393#if YOLOV5_V62
394 ex.extract("367", out);
395#elif YOLOV5_V60
396 ex.extract("401", out);
397#else
398 ex.extract("801", out);
399#endif
400 ncnn::Mat anchors(6);
401 anchors[0] = 116.f;
402 anchors[1] = 90.f;
403 anchors[2] = 156.f;
404 anchors[3] = 198.f;
405 anchors[4] = 373.f;
406 anchors[5] = 326.f;
407
408 std::vector<Object> objects32;
409 generate_proposals(anchors, 32, in_pad, out, prob_threshold, objects32);
410
411 proposals.insert(proposals.end(), objects32.begin(), objects32.end());
412 }
413
414 // sort all proposals by score from highest to lowest
415 qsort_descent_inplace(proposals);
416
417 // apply nms with nms_threshold
418 std::vector<int> picked;
419 nms_sorted_bboxes(proposals, picked, nms_threshold);
420
421 int count = picked.size();
422
423 objects.resize(count);
424 for (int i = 0; i < count; i++)
425 {
426 objects[i] = proposals[picked[i]];
427
428 // adjust offset to original unpadded
429 float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
430 float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
431 float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
432 float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
433
434 // clip
435 x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
436 y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
437 x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
438 y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
439
440 objects[i].rect.x = x0;
441 objects[i].rect.y = y0;
442 objects[i].rect.width = x1 - x0;
443 objects[i].rect.height = y1 - y0;
444 }
445
446 return 0;
447}
448
449static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
450{
451 static const char* class_names[] = {
452 "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
453 "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
454 "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
455 "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
456 "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
457 "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
458 "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
459 "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
460 "hair drier", "toothbrush"
461 };
462
463 cv::Mat image = bgr.clone();
464
465 for (size_t i = 0; i < objects.size(); i++)
466 {
467 const Object& obj = objects[i];
468
469 fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
470 obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
471
472 cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
473
474 char text[256];
475 sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
476
477 int baseLine = 0;
478 cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
479
480 int x = obj.rect.x;
481 int y = obj.rect.y - label_size.height - baseLine;
482 if (y < 0)
483 y = 0;
484 if (x + label_size.width > image.cols)
485 x = image.cols - label_size.width;
486
487 cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
488 cv::Scalar(255, 255, 255), -1);
489
490 cv::putText(image, text, cv::Point(x, y + label_size.height),
491 cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
492 }
493
494 cv::imshow("image", image);
495 cv::waitKey(0);
496}
497
498int main(int argc, char** argv)
499{
500 if (argc != 2)
501 {
502 fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
503 return -1;
504 }
505
506 const char* imagepath = argv[1];
507
508 cv::Mat m = cv::imread(imagepath, 1);
509 if (m.empty())
510 {
511 fprintf(stderr, "cv::imread %s failed\n", imagepath);
512 return -1;
513 }
514
515 std::vector<Object> objects;
516 detect_yolov5(m, objects);
517
518 draw_objects(m, objects);
519
520 return 0;
521}