Elffuss BraidHub

kikocis/ncnn public

master · 12.5 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 "net.h"
16
17#if defined(USE_NCNN_SIMPLEOCV)
18#include "simpleocv.h"
19#else
20#include <opencv2/core/core.hpp>
21#include <opencv2/highgui/highgui.hpp>
22#include <opencv2/imgproc/imgproc.hpp>
23#endif
24#include <stdlib.h>
25#include <float.h>
26#include <stdio.h>
27#include <vector>
28
29struct Object
30{
31 cv::Rect_<float> rect;
32 int label;
33 float prob;
34};
35
36static inline float intersection_area(const Object& a, const Object& b)
37{
38 cv::Rect_<float> inter = a.rect & b.rect;
39 return inter.area();
40}
41
42static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
43{
44 int i = left;
45 int j = right;
46 float p = faceobjects[(left + right) / 2].prob;
47
48 while (i <= j)
49 {
50 while (faceobjects[i].prob > p)
51 i++;
52
53 while (faceobjects[j].prob < p)
54 j--;
55
56 if (i <= j)
57 {
58 // swap
59 std::swap(faceobjects[i], faceobjects[j]);
60
61 i++;
62 j--;
63 }
64 }
65
66 #pragma omp parallel sections
67 {
68 #pragma omp section
69 {
70 if (left < j) qsort_descent_inplace(faceobjects, left, j);
71 }
72 #pragma omp section
73 {
74 if (i < right) qsort_descent_inplace(faceobjects, i, right);
75 }
76 }
77}
78
79static void qsort_descent_inplace(std::vector<Object>& faceobjects)
80{
81 if (faceobjects.empty())
82 return;
83
84 qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
85}
86
87static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
88{
89 picked.clear();
90
91 const int n = faceobjects.size();
92
93 std::vector<float> areas(n);
94 for (int i = 0; i < n; i++)
95 {
96 areas[i] = faceobjects[i].rect.area();
97 }
98
99 for (int i = 0; i < n; i++)
100 {
101 const Object& a = faceobjects[i];
102
103 int keep = 1;
104 for (int j = 0; j < (int)picked.size(); j++)
105 {
106 const Object& b = faceobjects[picked[j]];
107
108 if (!agnostic && a.label != b.label)
109 continue;
110
111 // intersection over union
112 float inter_area = intersection_area(a, b);
113 float union_area = areas[i] + areas[picked[j]] - inter_area;
114 // float IoU = inter_area / union_area
115 if (inter_area / union_area > nms_threshold)
116 keep = 0;
117 }
118
119 if (keep)
120 picked.push_back(i);
121 }
122}
123
124static inline float sigmoid(float x)
125{
126 return 1.0f / (1.0f + exp(-x));
127}
128
129static void generate_proposals(const ncnn::Mat& pred, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
130{
131 const int num_grid = pred.h;
132
133 int num_grid_x = pred.w;
134 int num_grid_y = pred.h;
135
136 const int num_class = 80; // number of classes. 80 for COCO
137 const int reg_max_1 = (pred.c - num_class) / 4;
138
139 for (int i = 0; i < num_grid_y; i++)
140 {
141 for (int j = 0; j < num_grid_x; j++)
142 {
143 // find label with max score
144 int label = -1;
145 float score = -FLT_MAX;
146 for (int k = 0; k < num_class; k++)
147 {
148 float s = pred.channel(k).row(i)[j];
149 if (s > score)
150 {
151 label = k;
152 score = s;
153 }
154 }
155
156 score = sigmoid(score);
157
158 if (score >= prob_threshold)
159 {
160 ncnn::Mat bbox_pred(reg_max_1, 4);
161 for (int k = 0; k < reg_max_1 * 4; k++)
162 {
163 bbox_pred[k] = pred.channel(num_class + k).row(i)[j];
164 }
165 {
166 ncnn::Layer* softmax = ncnn::create_layer("Softmax");
167
168 ncnn::ParamDict pd;
169 pd.set(0, 1); // axis
170 pd.set(1, 1);
171 softmax->load_param(pd);
172
173 ncnn::Option opt;
174 opt.num_threads = 1;
175 opt.use_packing_layout = false;
176
177 softmax->create_pipeline(opt);
178
179 softmax->forward_inplace(bbox_pred, opt);
180
181 softmax->destroy_pipeline(opt);
182
183 delete softmax;
184 }
185
186 float pred_ltrb[4];
187 for (int k = 0; k < 4; k++)
188 {
189 float dis = 0.f;
190 const float* dis_after_sm = bbox_pred.row(k);
191 for (int l = 0; l < reg_max_1; l++)
192 {
193 dis += l * dis_after_sm[l];
194 }
195
196 pred_ltrb[k] = dis * stride;
197 }
198
199 float pb_cx = j * stride;
200 float pb_cy = i * stride;
201
202 float x0 = pb_cx - pred_ltrb[0];
203 float y0 = pb_cy - pred_ltrb[1];
204 float x1 = pb_cx + pred_ltrb[2];
205 float y1 = pb_cy + pred_ltrb[3];
206
207 Object obj;
208 obj.rect.x = x0;
209 obj.rect.y = y0;
210 obj.rect.width = x1 - x0;
211 obj.rect.height = y1 - y0;
212 obj.label = label;
213 obj.prob = score;
214
215 objects.push_back(obj);
216 }
217 }
218 }
219}
220
221static int detect_nanodet(const cv::Mat& bgr, std::vector<Object>& objects)
222{
223 ncnn::Net nanodet;
224
225 nanodet.opt.use_vulkan_compute = true;
226 // nanodet.opt.use_bf16_storage = true;
227
228 // original pretrained model from https://github.com/RangiLyu/nanodet
229 // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
230 // nanodet.load_param("nanodet-plus-m_320.torchscript.ncnn.param");
231 // nanodet.load_model("nanodet-plus-m_320.torchscript.ncnn.bin");
232 if (nanodet.load_param("nanodet-plus-m_416.torchscript.ncnn.param"))
233 exit(-1);
234 if (nanodet.load_model("nanodet-plus-m_416.torchscript.ncnn.bin"))
235 exit(-1);
236
237 int width = bgr.cols;
238 int height = bgr.rows;
239
240 // const int target_size = 320;
241 const int target_size = 416;
242 const float prob_threshold = 0.4f;
243 const float nms_threshold = 0.5f;
244
245 // pad to multiple of 32
246 int w = width;
247 int h = height;
248 float scale = 1.f;
249 if (w > h)
250 {
251 scale = (float)target_size / w;
252 w = target_size;
253 h = h * scale;
254 }
255 else
256 {
257 scale = (float)target_size / h;
258 h = target_size;
259 w = w * scale;
260 }
261
262 ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, width, height, w, h);
263
264 // pad to target_size rectangle
265 int wpad = (w + 31) / 32 * 32 - w;
266 int hpad = (h + 31) / 32 * 32 - h;
267 ncnn::Mat in_pad;
268 ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f);
269
270 const float mean_vals[3] = {103.53f, 116.28f, 123.675f};
271 const float norm_vals[3] = {0.017429f, 0.017507f, 0.017125f};
272 in_pad.substract_mean_normalize(mean_vals, norm_vals);
273
274 ncnn::Extractor ex = nanodet.create_extractor();
275
276 ex.input("in0", in_pad);
277
278 std::vector<Object> proposals;
279
280 // stride 8
281 {
282 ncnn::Mat pred;
283 ex.extract("231", pred);
284
285 std::vector<Object> objects8;
286 generate_proposals(pred, 8, in_pad, prob_threshold, objects8);
287
288 proposals.insert(proposals.end(), objects8.begin(), objects8.end());
289 }
290
291 // stride 16
292 {
293 ncnn::Mat pred;
294 ex.extract("228", pred);
295
296 std::vector<Object> objects16;
297 generate_proposals(pred, 16, in_pad, prob_threshold, objects16);
298
299 proposals.insert(proposals.end(), objects16.begin(), objects16.end());
300 }
301
302 // stride 32
303 {
304 ncnn::Mat pred;
305 ex.extract("225", pred);
306
307 std::vector<Object> objects32;
308 generate_proposals(pred, 32, in_pad, prob_threshold, objects32);
309
310 proposals.insert(proposals.end(), objects32.begin(), objects32.end());
311 }
312
313 // stride 64
314 {
315 ncnn::Mat pred;
316 ex.extract("222", pred);
317
318 std::vector<Object> objects64;
319 generate_proposals(pred, 64, in_pad, prob_threshold, objects64);
320
321 proposals.insert(proposals.end(), objects64.begin(), objects64.end());
322 }
323
324 // sort all proposals by score from highest to lowest
325 qsort_descent_inplace(proposals);
326
327 // apply nms with nms_threshold
328 std::vector<int> picked;
329 nms_sorted_bboxes(proposals, picked, nms_threshold);
330
331 int count = picked.size();
332
333 objects.resize(count);
334 for (int i = 0; i < count; i++)
335 {
336 objects[i] = proposals[picked[i]];
337
338 // adjust offset to original unpadded
339 float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
340 float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
341 float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
342 float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
343
344 // clip
345 x0 = std::max(std::min(x0, (float)(width - 1)), 0.f);
346 y0 = std::max(std::min(y0, (float)(height - 1)), 0.f);
347 x1 = std::max(std::min(x1, (float)(width - 1)), 0.f);
348 y1 = std::max(std::min(y1, (float)(height - 1)), 0.f);
349
350 objects[i].rect.x = x0;
351 objects[i].rect.y = y0;
352 objects[i].rect.width = x1 - x0;
353 objects[i].rect.height = y1 - y0;
354 }
355
356 return 0;
357}
358
359static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
360{
361 static const char* class_names[] = {
362 "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
363 "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
364 "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
365 "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
366 "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
367 "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
368 "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
369 "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
370 "hair drier", "toothbrush"
371 };
372
373 cv::Mat image = bgr.clone();
374
375 for (size_t i = 0; i < objects.size(); i++)
376 {
377 const Object& obj = objects[i];
378
379 fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
380 obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
381
382 cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
383
384 char text[256];
385 sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
386
387 int baseLine = 0;
388 cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
389
390 int x = obj.rect.x;
391 int y = obj.rect.y - label_size.height - baseLine;
392 if (y < 0)
393 y = 0;
394 if (x + label_size.width > image.cols)
395 x = image.cols - label_size.width;
396
397 cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
398 cv::Scalar(255, 255, 255), -1);
399
400 cv::putText(image, text, cv::Point(x, y + label_size.height),
401 cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
402 }
403
404 cv::imshow("image", image);
405 cv::waitKey(0);
406}
407
408int main(int argc, char** argv)
409{
410 if (argc != 2)
411 {
412 fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
413 return -1;
414 }
415
416 const char* imagepath = argv[1];
417
418 cv::Mat m = cv::imread(imagepath, 1);
419 if (m.empty())
420 {
421 fprintf(stderr, "cv::imread %s failed\n", imagepath);
422 return -1;
423 }
424
425 std::vector<Object> objects;
426 detect_nanodet(m, objects);
427
428 draw_objects(m, objects);
429
430 return 0;
431}