Elffuss BraidHub

kikocis/ncnn public

master · 10.1 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2018 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#include <math.h>
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 <stdio.h>
26
27struct Object
28{
29 cv::Rect_<float> rect;
30 int label;
31 float prob;
32};
33
34static inline float intersection_area(const Object& a, const Object& b)
35{
36 cv::Rect_<float> inter = a.rect & b.rect;
37 return inter.area();
38}
39
40static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
41{
42 int i = left;
43 int j = right;
44 float p = objects[(left + right) / 2].prob;
45
46 while (i <= j)
47 {
48 while (objects[i].prob > p)
49 i++;
50
51 while (objects[j].prob < p)
52 j--;
53
54 if (i <= j)
55 {
56 // swap
57 std::swap(objects[i], objects[j]);
58
59 i++;
60 j--;
61 }
62 }
63
64 #pragma omp parallel sections
65 {
66 #pragma omp section
67 {
68 if (left < j) qsort_descent_inplace(objects, left, j);
69 }
70 #pragma omp section
71 {
72 if (i < right) qsort_descent_inplace(objects, i, right);
73 }
74 }
75}
76
77static void qsort_descent_inplace(std::vector<Object>& objects)
78{
79 if (objects.empty())
80 return;
81
82 qsort_descent_inplace(objects, 0, objects.size() - 1);
83}
84
85static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
86{
87 picked.clear();
88
89 const int n = faceobjects.size();
90
91 std::vector<float> areas(n);
92 for (int i = 0; i < n; i++)
93 {
94 areas[i] = faceobjects[i].rect.area();
95 }
96
97 for (int i = 0; i < n; i++)
98 {
99 const Object& a = faceobjects[i];
100
101 int keep = 1;
102 for (int j = 0; j < (int)picked.size(); j++)
103 {
104 const Object& b = faceobjects[picked[j]];
105
106 if (!agnostic && a.label != b.label)
107 continue;
108
109 // intersection over union
110 float inter_area = intersection_area(a, b);
111 float union_area = areas[i] + areas[picked[j]] - inter_area;
112 // float IoU = inter_area / union_area
113 if (inter_area / union_area > nms_threshold)
114 keep = 0;
115 }
116
117 if (keep)
118 picked.push_back(i);
119 }
120}
121
122static int detect_fasterrcnn(const cv::Mat& bgr, std::vector<Object>& objects)
123{
124 ncnn::Net fasterrcnn;
125
126 fasterrcnn.opt.use_vulkan_compute = true;
127
128 // original pretrained model from https://github.com/rbgirshick/py-faster-rcnn
129 // py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/faster_rcnn_test.pt
130 // https://dl.dropboxusercontent.com/s/o6ii098bu51d139/faster_rcnn_models.tgz?dl=0
131 // ZF_faster_rcnn_final.caffemodel
132 // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
133 if (fasterrcnn.load_param("ZF_faster_rcnn_final.param"))
134 exit(-1);
135 if (fasterrcnn.load_model("ZF_faster_rcnn_final.bin"))
136 exit(-1);
137
138 // hyper parameters taken from
139 // py-faster-rcnn/lib/fast_rcnn/config.py
140 // py-faster-rcnn/lib/fast_rcnn/test.py
141 const int target_size = 600; // __C.TEST.SCALES
142
143 const int max_per_image = 100;
144 const float confidence_thresh = 0.05f;
145
146 const float nms_threshold = 0.3f; // __C.TEST.NMS
147
148 // scale to target detect size
149 int w = bgr.cols;
150 int h = bgr.rows;
151 float scale = 1.f;
152 if (w < h)
153 {
154 scale = (float)target_size / w;
155 w = target_size;
156 h = h * scale;
157 }
158 else
159 {
160 scale = (float)target_size / h;
161 h = target_size;
162 w = w * scale;
163 }
164
165 ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, w, h);
166
167 const float mean_vals[3] = {102.9801f, 115.9465f, 122.7717f};
168 in.substract_mean_normalize(mean_vals, 0);
169
170 ncnn::Mat im_info(3);
171 im_info[0] = h;
172 im_info[1] = w;
173 im_info[2] = scale;
174
175 // step1, extract feature and all rois
176 ncnn::Extractor ex1 = fasterrcnn.create_extractor();
177
178 ex1.input("data", in);
179 ex1.input("im_info", im_info);
180
181 ncnn::Mat conv5_relu5; // feature
182 ncnn::Mat rois; // all rois
183 ex1.extract("conv5_relu5", conv5_relu5);
184 ex1.extract("rois", rois);
185
186 // step2, extract bbox and score for each roi
187 std::vector<std::vector<Object> > class_candidates;
188 for (int i = 0; i < rois.c; i++)
189 {
190 ncnn::Extractor ex2 = fasterrcnn.create_extractor();
191
192 ncnn::Mat roi = rois.channel(i); // get single roi
193 ex2.input("conv5_relu5", conv5_relu5);
194 ex2.input("rois", roi);
195
196 ncnn::Mat bbox_pred;
197 ncnn::Mat cls_prob;
198 ex2.extract("bbox_pred", bbox_pred);
199 ex2.extract("cls_prob", cls_prob);
200
201 int num_class = cls_prob.w;
202 class_candidates.resize(num_class);
203
204 // find class id with highest score
205 int label = 0;
206 float score = 0.f;
207 for (int i = 0; i < num_class; i++)
208 {
209 float class_score = cls_prob[i];
210 if (class_score > score)
211 {
212 label = i;
213 score = class_score;
214 }
215 }
216
217 // ignore background or low score
218 if (label == 0 || score <= confidence_thresh)
219 continue;
220
221 // fprintf(stderr, "%d = %f\n", label, score);
222
223 // unscale to image size
224 float x1 = roi[0] / scale;
225 float y1 = roi[1] / scale;
226 float x2 = roi[2] / scale;
227 float y2 = roi[3] / scale;
228
229 float pb_w = x2 - x1 + 1;
230 float pb_h = y2 - y1 + 1;
231
232 // apply bbox regression
233 float dx = bbox_pred[label * 4];
234 float dy = bbox_pred[label * 4 + 1];
235 float dw = bbox_pred[label * 4 + 2];
236 float dh = bbox_pred[label * 4 + 3];
237
238 float cx = x1 + pb_w * 0.5f;
239 float cy = y1 + pb_h * 0.5f;
240
241 float obj_cx = cx + pb_w * dx;
242 float obj_cy = cy + pb_h * dy;
243
244 float obj_w = pb_w * exp(dw);
245 float obj_h = pb_h * exp(dh);
246
247 float obj_x1 = obj_cx - obj_w * 0.5f;
248 float obj_y1 = obj_cy - obj_h * 0.5f;
249 float obj_x2 = obj_cx + obj_w * 0.5f;
250 float obj_y2 = obj_cy + obj_h * 0.5f;
251
252 // clip
253 obj_x1 = std::max(std::min(obj_x1, (float)(bgr.cols - 1)), 0.f);
254 obj_y1 = std::max(std::min(obj_y1, (float)(bgr.rows - 1)), 0.f);
255 obj_x2 = std::max(std::min(obj_x2, (float)(bgr.cols - 1)), 0.f);
256 obj_y2 = std::max(std::min(obj_y2, (float)(bgr.rows - 1)), 0.f);
257
258 // append object
259 Object obj;
260 obj.rect = cv::Rect_<float>(obj_x1, obj_y1, obj_x2 - obj_x1 + 1, obj_y2 - obj_y1 + 1);
261 obj.label = label;
262 obj.prob = score;
263
264 class_candidates[label].push_back(obj);
265 }
266
267 // post process
268 objects.clear();
269 for (int i = 0; i < (int)class_candidates.size(); i++)
270 {
271 std::vector<Object>& candidates = class_candidates[i];
272
273 qsort_descent_inplace(candidates);
274
275 std::vector<int> picked;
276 nms_sorted_bboxes(candidates, picked, nms_threshold);
277
278 for (int j = 0; j < (int)picked.size(); j++)
279 {
280 int z = picked[j];
281 objects.push_back(candidates[z]);
282 }
283 }
284
285 qsort_descent_inplace(objects);
286
287 if (max_per_image > 0 && max_per_image < objects.size())
288 {
289 objects.resize(max_per_image);
290 }
291
292 return 0;
293}
294
295static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
296{
297 static const char* class_names[] = {"background",
298 "aeroplane", "bicycle", "bird", "boat",
299 "bottle", "bus", "car", "cat", "chair",
300 "cow", "diningtable", "dog", "horse",
301 "motorbike", "person", "pottedplant",
302 "sheep", "sofa", "train", "tvmonitor"
303 };
304
305 cv::Mat image = bgr.clone();
306
307 for (size_t i = 0; i < objects.size(); i++)
308 {
309 const Object& obj = objects[i];
310
311 fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
312 obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
313
314 cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
315
316 char text[256];
317 sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
318
319 int baseLine = 0;
320 cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
321
322 int x = obj.rect.x;
323 int y = obj.rect.y - label_size.height - baseLine;
324 if (y < 0)
325 y = 0;
326 if (x + label_size.width > image.cols)
327 x = image.cols - label_size.width;
328
329 cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
330 cv::Scalar(255, 255, 255), -1);
331
332 cv::putText(image, text, cv::Point(x, y + label_size.height),
333 cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
334 }
335
336 cv::imshow("image", image);
337 cv::waitKey(0);
338}
339
340int main(int argc, char** argv)
341{
342 if (argc != 2)
343 {
344 fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
345 return -1;
346 }
347
348 const char* imagepath = argv[1];
349
350 cv::Mat m = cv::imread(imagepath, 1);
351 if (m.empty())
352 {
353 fprintf(stderr, "cv::imread %s failed\n", imagepath);
354 return -1;
355 }
356
357 std::vector<Object> objects;
358 detect_fasterrcnn(m, objects);
359
360 draw_objects(m, objects);
361
362 return 0;
363}