Elffuss BraidHub

kikocis/ncnn public

e91df65e9177 · 9.9 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_rfcn(const cv::Mat& bgr, std::vector<Object>& objects)
123{
124 ncnn::Net rfcn;
125
126 rfcn.opt.use_vulkan_compute = true;
127
128 // original pretrained model from https://github.com/YuwenXiong/py-R-FCN
129 // https://github.com/YuwenXiong/py-R-FCN/blob/master/models/pascal_voc/ResNet-50/rfcn_end2end/test_agnostic.prototxt
130 // https://1drv.ms/u/s!AoN7vygOjLIQqUWHpY67oaC7mopf
131 // resnet50_rfcn_final.caffemodel
132 if (rfcn.load_param("rfcn_end2end.param"))
133 exit(-1);
134 if (rfcn.load_model("rfcn_end2end.bin"))
135 exit(-1);
136
137 const int target_size = 224;
138
139 const int max_per_image = 100;
140 const float confidence_thresh = 0.6f; // CONF_THRESH
141
142 const float nms_threshold = 0.3f; // NMS_THRESH
143
144 // scale to target detect size
145 int w = bgr.cols;
146 int h = bgr.rows;
147 float scale = 1.f;
148 if (w < h)
149 {
150 scale = (float)target_size / w;
151 w = target_size;
152 h = h * scale;
153 }
154 else
155 {
156 scale = (float)target_size / h;
157 h = target_size;
158 w = w * scale;
159 }
160
161 ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, w, h);
162
163 const float mean_vals[3] = {102.9801f, 115.9465f, 122.7717f};
164 in.substract_mean_normalize(mean_vals, 0);
165
166 ncnn::Mat im_info(3);
167 im_info[0] = h;
168 im_info[1] = w;
169 im_info[2] = scale;
170
171 // step1, extract feature and all rois
172 ncnn::Extractor ex1 = rfcn.create_extractor();
173
174 ex1.input("data", in);
175 ex1.input("im_info", im_info);
176
177 ncnn::Mat rfcn_cls;
178 ncnn::Mat rfcn_bbox;
179 ncnn::Mat rois; // all rois
180 ex1.extract("rfcn_cls", rfcn_cls);
181 ex1.extract("rfcn_bbox", rfcn_bbox);
182 ex1.extract("rois", rois);
183
184 // step2, extract bbox and score for each roi
185 std::vector<std::vector<Object> > class_candidates;
186 for (int i = 0; i < rois.c; i++)
187 {
188 ncnn::Extractor ex2 = rfcn.create_extractor();
189
190 ncnn::Mat roi = rois.channel(i); // get single roi
191 ex2.input("rfcn_cls", rfcn_cls);
192 ex2.input("rfcn_bbox", rfcn_bbox);
193 ex2.input("rois", roi);
194
195 ncnn::Mat bbox_pred;
196 ncnn::Mat cls_prob;
197 ex2.extract("bbox_pred", bbox_pred);
198 ex2.extract("cls_prob", cls_prob);
199
200 int num_class = cls_prob.w;
201 class_candidates.resize(num_class);
202
203 // find class id with highest score
204 int label = 0;
205 float score = 0.f;
206 for (int i = 0; i < num_class; i++)
207 {
208 float class_score = cls_prob[i];
209 if (class_score > score)
210 {
211 label = i;
212 score = class_score;
213 }
214 }
215
216 // ignore background or low score
217 if (label == 0 || score <= confidence_thresh)
218 continue;
219
220 // fprintf(stderr, "%d = %f\n", label, score);
221
222 // unscale to image size
223 float x1 = roi[0] / scale;
224 float y1 = roi[1] / scale;
225 float x2 = roi[2] / scale;
226 float y2 = roi[3] / scale;
227
228 float pb_w = x2 - x1 + 1;
229 float pb_h = y2 - y1 + 1;
230
231 // apply bbox regression
232 float dx = bbox_pred[4];
233 float dy = bbox_pred[4 + 1];
234 float dw = bbox_pred[4 + 2];
235 float dh = bbox_pred[4 + 3];
236
237 float cx = x1 + pb_w * 0.5f;
238 float cy = y1 + pb_h * 0.5f;
239
240 float obj_cx = cx + pb_w * dx;
241 float obj_cy = cy + pb_h * dy;
242
243 float obj_w = pb_w * exp(dw);
244 float obj_h = pb_h * exp(dh);
245
246 float obj_x1 = obj_cx - obj_w * 0.5f;
247 float obj_y1 = obj_cy - obj_h * 0.5f;
248 float obj_x2 = obj_cx + obj_w * 0.5f;
249 float obj_y2 = obj_cy + obj_h * 0.5f;
250
251 // clip
252 obj_x1 = std::max(std::min(obj_x1, (float)(bgr.cols - 1)), 0.f);
253 obj_y1 = std::max(std::min(obj_y1, (float)(bgr.rows - 1)), 0.f);
254 obj_x2 = std::max(std::min(obj_x2, (float)(bgr.cols - 1)), 0.f);
255 obj_y2 = std::max(std::min(obj_y2, (float)(bgr.rows - 1)), 0.f);
256
257 // append object
258 Object obj;
259 obj.rect = cv::Rect_<float>(obj_x1, obj_y1, obj_x2 - obj_x1 + 1, obj_y2 - obj_y1 + 1);
260 obj.label = label;
261 obj.prob = score;
262
263 class_candidates[label].push_back(obj);
264 }
265
266 // post process
267 objects.clear();
268 for (int i = 0; i < (int)class_candidates.size(); i++)
269 {
270 std::vector<Object>& candidates = class_candidates[i];
271
272 qsort_descent_inplace(candidates);
273
274 std::vector<int> picked;
275 nms_sorted_bboxes(candidates, picked, nms_threshold);
276
277 for (int j = 0; j < (int)picked.size(); j++)
278 {
279 int z = picked[j];
280 objects.push_back(candidates[z]);
281 }
282 }
283
284 qsort_descent_inplace(objects);
285
286 if (max_per_image > 0 && max_per_image < objects.size())
287 {
288 objects.resize(max_per_image);
289 }
290
291 return 0;
292}
293
294static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
295{
296 static const char* class_names[] = {"background",
297 "aeroplane", "bicycle", "bird", "boat",
298 "bottle", "bus", "car", "cat", "chair",
299 "cow", "diningtable", "dog", "horse",
300 "motorbike", "person", "pottedplant",
301 "sheep", "sofa", "train", "tvmonitor"
302 };
303
304 cv::Mat image = bgr.clone();
305
306 for (size_t i = 0; i < objects.size(); i++)
307 {
308 const Object& obj = objects[i];
309
310 fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
311 obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
312
313 cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
314
315 char text[256];
316 sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
317
318 int baseLine = 0;
319 cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
320
321 int x = obj.rect.x;
322 int y = obj.rect.y - label_size.height - baseLine;
323 if (y < 0)
324 y = 0;
325 if (x + label_size.width > image.cols)
326 x = image.cols - label_size.width;
327
328 cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
329 cv::Scalar(255, 255, 255), -1);
330
331 cv::putText(image, text, cv::Point(x, y + label_size.height),
332 cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
333 }
334
335 cv::imshow("image", image);
336 cv::waitKey(0);
337}
338
339int main(int argc, char** argv)
340{
341 if (argc != 2)
342 {
343 fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
344 return -1;
345 }
346
347 const char* imagepath = argv[1];
348
349 cv::Mat m = cv::imread(imagepath, 1);
350 if (m.empty())
351 {
352 fprintf(stderr, "cv::imread %s failed\n", imagepath);
353 return -1;
354 }
355
356 std::vector<Object> objects;
357 detect_rfcn(m, objects);
358
359 draw_objects(m, objects);
360
361 return 0;
362}